-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1742 lines (1482 loc) · 88.9 KB
/
index.html
File metadata and controls
1742 lines (1482 loc) · 88.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Intro to R</title>
<meta name="description" content="A hands-on, interactive R guide for watershed ecology. Learn variables, data frames, linear models, and ggplot2 in a watershed ecological context." />
<link rel="icon" href="./img/R-Intro-logo.png" />
<!-- Fonts: a distinctive editorial pairing -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Serif+4:ital,opsz,wght@0,8..60,400;0,8..60,600;0,8..60,700;1,8..60,400;1,8..60,600&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
<!-- Highlight.js for R syntax highlighting -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-light.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/r.min.js"></script>
<!-- coi-serviceworker enables COOP/COEP headers via service worker
so that SharedArrayBuffer (required by WebR) works on GitHub Pages.
MUST be loaded before WebR. -->
<script src="./coi-serviceworker.js"></script>
<!-- Assessment specifications (plain script — loads even if WebR fails) -->
<script src="./js/assessments.js"></script>
<!-- R Markdown export — turns the page into a downloadable .Rmd document -->
<script src="./js/rmd-export.js"></script>
<!-- WebR for in-browser R execution -->
<script type="module" src="./js/runner.js"></script>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<!-- Sticky reading progress -->
<div class="progress-bar"><div class="progress-fill" id="progress-fill"></div></div>
<!-- Top banner -->
<header class="hero">
<div class="hero-inner">
<div class="hero-meta">
<span class="meta-tag">Field Manual</span>
<span class="meta-divider">·</span>
<span class="meta-tag">v2.02</span>
<span class="meta-divider">·</span>
<span class="meta-tag">Watershed Ecology</span>
</div>
<h1 class="hero-title">
<span class="hero-overline">An Introduction to</span>
<span class="hero-display">R for<br/><em>Watershed Ecology</em></span>
</h1>
<p class="hero-sub">A hands-on, interactive guide for students with varying levels of programming experience. Read, run, and modify real R code directly in your browser.</p>
<div class="hero-actions">
<a class="btn-primary" href="#section-1">Begin reading <span aria-hidden="true">→</span></a>
<a class="btn-secondary" href="#about">About this guide</a>
<button class="btn-tertiary" data-rmd-download type="button" title="Download an R Markdown (.Rmd) version of this guide for offline practice">
<span class="btn-tertiary-icon" aria-hidden="true">↓</span> Download as R Markdown
</button>
</div>
</div>
<svg class="hero-stream" viewBox="0 0 1200 220" preserveAspectRatio="none" aria-hidden="true">
<defs>
<linearGradient id="streamGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="var(--water-mid)" stop-opacity="0.0"/>
<stop offset="100%" stop-color="var(--water-deep)" stop-opacity="0.4"/>
</linearGradient>
</defs>
<path d="M0,140 C200,80 400,200 600,120 C800,40 1000,180 1200,100 L1200,220 L0,220 Z" fill="url(#streamGrad)"/>
<path d="M0,160 C200,120 400,210 600,150 C800,90 1000,200 1200,140" fill="none" stroke="var(--water-mid)" stroke-width="1" stroke-opacity="0.5"/>
<path d="M0,180 C200,150 400,215 600,175 C800,135 1000,210 1200,165" fill="none" stroke="var(--water-mid)" stroke-width="1" stroke-opacity="0.3"/>
</svg>
</header>
<!-- Layout: TOC + content -->
<div class="layout">
<aside class="toc" aria-label="Table of contents">
<details class="toc-details" open>
<summary class="toc-summary">
<span class="toc-summary-label">Contents</span>
<span class="toc-summary-current" aria-hidden="true"></span>
<span class="toc-summary-chevron" aria-hidden="true">▾</span>
</summary>
<div class="toc-inner">
<p class="toc-heading">Contents</p>
<ol class="toc-list">
<li><a href="#section-1"><span class="toc-num">01</span> Welcome to R</a></li>
<li><a href="#section-2"><span class="toc-num">02</span> Terminology</a></li>
<li><a href="#section-3"><span class="toc-num">03</span> Variables</a></li>
<li><a href="#section-4"><span class="toc-num">04</span> Vectors</a></li>
<li><a href="#section-5"><span class="toc-num">05</span> Data Frames</a></li>
<li><a href="#section-6"><span class="toc-num">06</span> Operators</a></li>
<li><a href="#section-7"><span class="toc-num">07</span> Equations to Code</a></li>
<li><a href="#section-8"><span class="toc-num">08</span> Column Math</a></li>
<li><a href="#section-9"><span class="toc-num">09</span> For Loops</a></li>
<li><a href="#section-10"><span class="toc-num">10</span> While Loops</a></li>
<li><a href="#section-11"><span class="toc-num">11</span> Linear Models</a></li>
<li><a href="#section-12"><span class="toc-num">12</span> Plotting (Base R)</a></li>
<li><a href="#section-13"><span class="toc-num">13</span> Plotting (ggplot2)</a></li>
<li><a href="#section-14"><span class="toc-num">14</span> Capstone</a></li>
<li><a href="#section-15"><span class="toc-num">15</span> Where to Go Next</a></li>
</ol>
<div class="toc-status">
<p class="toc-status-label">R engine</p>
<div class="r-status" id="r-status">
<span class="r-status-dot"></span>
<span class="r-status-text">Loading WebR…</span>
</div>
<p class="toc-help">First load takes ~30 seconds. Code cells run R right in your browser.</p>
</div>
</div>
</details>
</aside>
<main class="content">
<!-- ABOUT -->
<section id="about" class="callout-about">
<h2 class="about-title">How to use this guide</h2>
<div class="about-grid">
<div>
<p class="about-step"><span class="about-step-num">1</span> Each chapter introduces one concept with self-contained examples in code blocks. Click <strong>Run</strong> to execute the code, and output appears below the cell.</p>
</div>
<div>
<p class="about-step"><span class="about-step-num">2</span> Every exercise has an empty editor where you write your own code. Use <strong>Just run</strong> to test how it behaves, or <strong>Run & check</strong> to find out whether your answer is correct.</p>
</div>
<div>
<p class="about-step"><span class="about-step-num">3</span> Click <strong>Reveal solution</strong> when you're ready to compare. Try the exercise yourself first!</p>
</div>
</div>
<p class="about-note">⚠️ A note on errors: you <em>will</em> get error messages, and that's normal! Read them carefully — they're R telling you where it got confused. Resources for interpreting errors include Stack Overflow, GeeksforGeeks, or even the R Documentation itself.</p>
</section>
<!-- ============================================ -->
<!-- SECTION 1 -->
<!-- ============================================ -->
<section id="section-1" class="chapter">
<div class="chapter-header">
<span class="chapter-number">Chapter 01</span>
<h2 class="chapter-title">Welcome to R</h2>
</div>
<p>R is a free programming language built for working with data. In watershed ecology, it can be used for almost everything: analyzing stream chemistry, estimating discharge, modeling nutrient loads, examining macroinvertebrate community composition, and producing publication-quality figures from monitoring data. By the end of this guide, you'll be able to do real watershed data analysis in R.</p>
<p>You don't need any programming experience. We'll go step by step, and there are exercises throughout to help you practice. Each exercise is followed by a worked solution so you can check your answer and understand the reasoning.</p>
<h3>Two ways to use R</h3>
<p>You have two options for working with R. Both run the same R language; the difference is where the code lives.</p>
<p><strong>Right here in your browser.</strong> Every gray code cell on this page is a tiny live R session. Click <strong>Run</strong> and the code executes immediately, with output shown below the cell. You don't have to install anything. This is great for learning the language and working through this guide.</p>
<p><strong>On your own computer with R and RStudio.</strong> For real work — projects, assignments, research — you'll want R installed locally so you can save your work, manage data files, and use the full suite of R packages. The rest of this chapter walks you through installing both pieces and explains how the desktop environment compares to the in-browser cells you'll use here.</p>
<h3>Installing R and RStudio</h3>
<p>You need <strong>two</strong> separate downloads. R is the language itself. RStudio is the editor you use to write and run R code. Install R first, then RStudio.</p>
<h4>Step 1 — Install R</h4>
<p>Go to <a href="https://cran.r-project.org/" target="_blank" rel="noopener">cran.r-project.org</a> (the Comprehensive R Archive Network). Pick the link that matches your operating system:</p>
<ul>
<li><strong>Windows:</strong> Click "Download R for Windows" → "base" → "Download R-X.X.X for Windows". Run the installer with default settings.</li>
<li><strong>macOS:</strong> Click "Download R for macOS" and download the <code>.pkg</code> file matching your processor. Apple Silicon Macs (M1/M2/M3/M4) use the "arm64" build; older Intel Macs use the "x86_64" build. If you're not sure, click the Apple menu → About This Mac to check.</li>
<li><strong>Linux:</strong> Click "Download R for Linux" and follow the instructions for your distribution. On Ubuntu/Debian, the simplest command is <code>sudo apt install r-base</code>; on Fedora, <code>sudo dnf install R</code>. CRAN also has more recent builds maintained directly by the R project — check the page for your distribution.</li>
</ul>
<h4>Step 2 — Install RStudio</h4>
<p>Go to <a href="https://posit.co/download/rstudio-desktop/" target="_blank" rel="noopener">posit.co/download/rstudio-desktop</a>. (RStudio is now made by a company called Posit, but the software is still called RStudio.) The page should auto-detect your OS and show the right download. Run the installer.</p>
<p>Once both are installed, you only ever open <em>RStudio</em> — it finds and uses the R installation behind the scenes. You generally don't open R directly.</p>
<h3>What RStudio looks like</h3>
<p>When you open RStudio for the first time, you'll see a window divided into four panes. The screenshot below shows the typical layout:</p>
<figure class="rstudio-figure">
<img src="img/rstudio-layout.png" alt="RStudio's four-pane layout, showing the source editor, console, environment, and files panes" />
<figcaption>Screenshot of RStudio's four-pane layout</figcaption>
</figure>
<p>Each pane has a distinct job. Here's what they do:</p>
<ol class="rstudio-panes">
<li>
<strong>Source editor (top-left)</strong> — where you write and save R scripts. A script is just a text file ending in <code>.R</code> that contains R code. You type code here and run it line-by-line (with <kbd>Ctrl</kbd>+<kbd>Enter</kbd> on Windows/Linux, <kbd>Cmd</kbd>+<kbd>Return</kbd> on Mac), or run the whole script at once.
</li>
<li>
<strong>Environment / History (top-right)</strong> — shows everything currently in memory. Variables, vectors, data frames you've created — all listed here with their values or dimensions. Think of it as a live inventory of your R session. Clicking a data frame opens it in a spreadsheet-style viewer, which is really helpful for inspecting datasets. The History tab shows every command you've ever typed in the current session.
</li>
<li>
<strong>Console (bottom-left)</strong> — the live R prompt. Anything you type here is executed immediately and the result appears right below. The console is what's actually running your R commands; the Source editor pane is just a place to write code that you then send to the console. When you click "Run" on a code cell on this webpage, you can think of it as sending that cell's contents to a hidden console.
</li>
<li>
<strong>Files / Plots / Help / Packages / Viewer (bottom-right)</strong> — a multi-purpose pane.
<ul>
<li><em>Files</em> browses your project folder.</li>
<li><em>Plots</em> displays figures you create with <code>plot()</code>, <code>ggplot()</code>, etc. — you can flip back through every plot you've made.</li>
<li><em>Help</em> shows R's built-in documentation. Type <code>?mean</code> in the console and the help page for <code>mean()</code> appears here.</li>
<li><em>Packages</em> lists installed packages and lets you install new ones.</li>
<li><em>Viewer</em> shows HTML output (knit reports, interactive widgets).</li>
</ul>
</li>
</ol>
<h3>Projects and working directories</h3>
<p>Once you start doing real analyses you'll have a folder full of related files: your R scripts, raw data, figures, and notes. Two RStudio concepts help you keep them organized.</p>
<p><strong>The working directory.</strong> R has a notion of a "current folder" — the place it looks for files when you say things like <code>read.csv("nitrate.csv")</code>. That folder is called the <strong>working directory</strong>. You can ask R where it currently is with <code>getwd()</code>, and you can change it with <code>setwd("/path/to/folder")</code>. If R can't find a file you're trying to read, the most common reason is that your working directory is somewhere else and R is looking in the wrong place.</p>
<p><strong>RStudio Projects.</strong> An RStudio Project is just a folder with a small <code>.Rproj</code> file inside it. When you open a project (File → Open Project, or by double-clicking the <code>.Rproj</code> file), three useful things happen:</p>
<ul>
<li>Your working directory is automatically set to the project folder. No more <code>setwd()</code> with hardcoded paths.</li>
<li>RStudio remembers which scripts you had open last time, so you pick up where you left off.</li>
<li>Variables you defined in your last session can optionally be restored.</li>
</ul>
<p>The recommended workflow is: <strong>one project per analysis</strong>. For a class assignment, make a folder called something like <code>watershed-assessment</code>, create a new RStudio Project in it (File → New Project → New Directory), and put all your scripts and data inside. When you reopen the project a week later, you won't have to remember anything about where files live — R already knows.</p>
<p>A typical project folder might look like this:</p>
<ul>
<li><code>watershed-assessment/</code> — the project root
<ul>
<li><code>watershed-assessment.Rproj</code> — the project file</li>
<li><code>data/</code> — raw data files (CSVs, shapefiles)</li>
<li><code>scripts/</code> — your <code>.R</code> analysis scripts</li>
<li><code>figures/</code> — plots you generate</li>
<li><code>README.md</code> — a brief note describing the project</li>
</ul>
</li>
</ul>
<p>With this structure and a project file, references like <code>read.csv("data/nitrate.csv")</code> work the same on your laptop, your collaborator's laptop, and the lab computer. No absolute paths needed.</p>
<h3>The R authoring environment</h3>
<p>So far we've talked about R (the language) and RStudio (the editor). But when you start writing real analyses, you'll encounter a few more terms: <strong>IDE</strong>, <strong>R scripts</strong>, and <strong>R Markdown / Quarto documents</strong>. These are the three things that make up your day-to-day R workflow, and it's worth a quick tour before we head into the actual coding chapters.</p>
<h4>RStudio is an IDE</h4>
<p>RStudio is what's called an <strong>integrated development environment</strong>, or IDE for short. The name is more intimidating than the idea: an IDE is just a single application that bundles together the tools you need to write code. You've already seen the four panes — the source editor, the console, the environment viewer, and the files/plots/help pane. Each of those is a separate tool, but RStudio integrates them into one window so you don't have to juggle multiple programs.</p>
<p>Other languages have their own IDEs (VS Code, PyCharm, Eclipse, Xcode). For R, the dominant choice is RStudio. You could write R code in any plain text editor and run it from a terminal, but RStudio's tight integration of the console, plots, and help pages makes it dramatically more pleasant.</p>
<h4>R scripts: the standard file format</h4>
<p>An <strong>R script</strong> is a plain text file with the extension <code>.R</code>. It contains nothing but R code (and comments). When you run a script, R executes the lines from top to bottom as if you'd typed them into the console one at a time. Here's what a small script might look like:</p>
<div class="code-cell" data-cell-id="cell-1-script">
<div class="code-cell-header">
<span class="code-cell-label">Example: bear_creek_analysis.R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor"># Bear Creek nitrate analysis — May 2026
# Author: J. Doe
library(ggplot2)
# Load and summarize the data (simulated here for demonstration)
nitrate <- c(0.42, 1.85, 0.31, 2.94, 1.12, 0.58, 3.21, 0.27, 2.05, 1.43)
mean(nitrate)
sd(nitrate)</textarea>
<div class="code-output" data-output></div>
</div>
<p>Scripts are the right tool when your output <em>is</em> the analysis itself — a script that loads data, fits a model, and saves a figure to disk. They're the workhorses of reproducible research: anyone with the same data can run your <code>.R</code> file and get the same results. Most published analysis pipelines are built from one or more R scripts.</p>
<h4>R Markdown and Quarto: writing with code</h4>
<p>Sometimes the deliverable isn't just the analysis but a <em>document</em> — a lab report, a methods write-up, a thesis chapter. For these, plain R scripts aren't quite right because you also want explanations, headings, equations, figures, and tables, all woven together with the code that produced them.</p>
<p>That's what <strong>R Markdown</strong> (<code>.Rmd</code> files) and <strong>Quarto</strong> (<code>.qmd</code> files) are for. They're two closely-related formats — Quarto is Posit's newer, more flexible successor to R Markdown — that let you mix writing and code in one file. Quarto is increasingly the modern default, but the two work so similarly that you can treat them as one topic for now. We'll just call them "Rmd/Quarto" here.</p>
<p>Inside one of these files, prose is written as ordinary text (with markdown formatting for things like <strong>bold</strong> and headings), and R code lives in <strong>code chunks</strong>: small blocks fenced off by triple-backticks with <code>{r}</code> at the top. When you press <strong>Knit</strong> (for Rmd) or <strong>Render</strong> (for Quarto) in RStudio, the file is processed end-to-end: each code chunk runs, its output is captured (numbers, tables, figures), and everything is woven into a polished output document — usually HTML, PDF, or Word.</p>
<p>A typical chunk inside an Rmd/Quarto file looks like this:</p>
<div class="code-cell" data-cell-id="cell-1-rmd">
<div class="code-cell-header">
<span class="code-cell-label">Example chunk inside a .Rmd or .qmd document</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor"># Above this chunk, prose like "Figure 1 shows the nitrate gradient."
# (Imagine the prose written in normal text, not in this code cell.)
# The chunk itself runs as R code:
library(ggplot2)
gradient_data <- data.frame(
distance = c(0.1, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0),
nitrate = c(4.8, 4.2, 3.5, 3.1, 2.6, 1.9, 1.5, 1.1)
)
ggplot(gradient_data, aes(x = distance, y = nitrate)) +
geom_point() + geom_smooth(method = "lm")
# When the document is knitted, the figure appears here in place of the code,
# embedded between the surrounding paragraphs.</textarea>
<div class="code-output" data-output></div>
</div>
<p>For example: a watershed assessment lab report might have an introduction paragraph, a code chunk that loads the field data, another paragraph describing the analysis, a chunk that fits a linear model and prints the summary, then a chunk that produces a final figure — all in one <code>.Rmd</code> or <code>.qmd</code> file. When you knit it, the result is a single PDF or HTML document with the prose flowing naturally around the figures and tables generated by your code. No copy-pasting between R and Word. If the data updates, you just re-knit and everything regenerates.</p>
<h4>How this webpage compares to all of the above</h4>
<p>The code cells you'll use throughout this guide sit in an interesting middle ground. Conceptually, they're closest to <strong>Rmd/Quarto chunks</strong> — prose and runnable R code interleaved on a page — except that this page is fixed and you don't render anything. Compared to working in RStudio with real <code>.R</code> or <code>.qmd</code> files, the code cells here are intentionally simpler:</p>
<ul>
<li><strong>Persistence between cells.</strong> Each cell on this webpage runs in a fresh R environment, so variables you create in one cell are <em>not</em> automatically available in the next — that's why some exercises ask you to recreate a data frame at the top of your answer. In RStudio (script or notebook), your variables persist for the entire session.</li>
<li><strong>Saving your work.</strong> Code typed into a cell here lives only as long as the browser tab is open. <code>.R</code>, <code>.Rmd</code>, and <code>.qmd</code> files all save to your computer where you can edit, version-control with git, and share them.</li>
<li><strong>Packages.</strong> Only a handful of R packages are pre-loaded in your browser (we have <code>ggplot2</code>, but not the full tidyverse). In RStudio you can install any of the ~20,000 packages on CRAN with a single command.</li>
<li><strong>Data files.</strong> The cells here can't read CSVs or other files from your hard drive. In RStudio you'll routinely use <code>read.csv()</code>, <code>read_csv()</code>, or specialized functions like <code>dataRetrieval::readNWISdv()</code> to pull discharge records straight from the USGS.</li>
<li><strong>Knitting / rendering.</strong> This page is hand-written HTML; nothing gets rendered from a source document. With Rmd/Quarto, the file you write <em>is</em> the source — you knit it whenever you want to produce the final output.</li>
<li><strong>Speed.</strong> The browser version downloads R-compiled-to-WebAssembly the first time you visit, which takes ~30 seconds. R running locally through RStudio is at native speed once installed.</li>
</ul>
<p>The code cells here are good enough to work through this guide — you can focus on learning R without worrying about installation, file paths, or knitting. Once you're ready to do your own analyses, you'll likely use R scripts for the analysis itself and <code>.Rmd</code>/<code>.qmd</code> documents to write up the results. The beauty is that the R syntax you learn here works identically in all three.</p>
</section>
<!-- ============================================ -->
<!-- SECTION 2 — Terminology -->
<!-- ============================================ -->
<section id="section-2" class="chapter">
<div class="chapter-header">
<span class="chapter-number">Chapter 02</span>
<h2 class="chapter-title">Terminology</h2>
</div>
<p>Before you write your first line of R, a few vocabulary words will save you a lot of confusion. This short chapter introduces four terms — <strong>code</strong>, <strong>comments</strong>, <strong>functions</strong>, and <strong>operators</strong> — that show up on every page of this guide.</p>
<h3>Code and Comments</h3>
<p><strong>Code</strong> is just text — instructions written for the computer to follow. Each line tells R to do something specific. R reads your code top to bottom, one line at a time, and does exactly what you say. If R does something unexpected, it's because the code <em>told</em> it to. Reading the line carefully is almost always the first step in fixing a <strong>bug</strong> (or, problem in the code).</p>
<p>Lines that start with <code>#</code> are <strong>comments</strong> — notes for humans that R ignores completely. Comments are how you explain to your future self (or classmate/professor/colleague) what your code is doing:</p>
<div class="code-cell" data-cell-id="cell-2-1">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor"># This whole line is a comment. R ignores it.
2 + 2 # The 2 + 2 part runs; everything after # is a comment.</textarea>
<div class="code-output" data-output></div>
</div>
<h3>Functions</h3>
<p>A <strong>function</strong> is a named procedure that takes one or more inputs and gives back a result. You can think of a function like a labeled machine: you put something in, the machine does its job, and something comes out. R comes with thousands of functions built in, and you'll learn many of them throughout this guide.</p>
<p>You "call" (run) a function by writing its name followed by parentheses. Whatever you put inside the parentheses is the <strong>input</strong> (sometimes called an <em>argument</em>). For example, <code>sqrt()</code> is the square-root function:</p>
<div class="code-cell" data-cell-id="cell-2-2">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">sqrt(16) # input: 16, output: 4
sqrt(2) # input: 2, output: about 1.414
# Some functions take multiple inputs separated by commas
round(3.14159, 2) # input: a number and a digit count; output: 3.14</textarea>
<div class="code-output" data-output></div>
</div>
<p>The parentheses are essential. <code>sqrt(16)</code> calls the function on 16, but <code>sqrt</code> by itself just refers to the function as an object — like saying the word "calculator" instead of actually using one. Forgetting parentheses, or having them in the wrong place, is a common source of error for beginners.</p>
<p>You'll see this same pattern everywhere in R. <code>mean(x)</code> takes a vector <code>x</code> and gives back its average. <code>length(x)</code> gives you how many items are in <code>x</code>. <code>read.csv("nitrate.csv")</code> reads a CSV file. The pattern is always <em>function-name</em> followed by parentheses around the input.</p>
<p>Arguments aren't always required for a function (e.g., <code>getwd()</code> is a function that returns your current working directory). Sometimes arguments have default values, so you don't have to specify them each time. If you're curious about the arguments a function accepts, you can use the help function <code>?function_name</code> to view its documentation.</p>
<h3>Operators</h3>
<p>An <strong>operator</strong> is a special shortcut symbol that acts like a tiny function. You've used them in math your whole life: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>. R has the same arithmetic operators, plus a few R-specific ones like <code><-</code> (used to store values in variables, which we'll see in the next chapter) and <code>==</code> (which checks whether two things are equal).</p>
<p>Operators don't use parentheses around their inputs — they sit between them. So <code>2 + 3</code> is an operator (<code>+</code>) acting on two numbers, while <code>sum(2, 3)</code> is a function (<code>sum</code>) acting on two numbers. Both give 5; the syntax is just different.</p>
<p>That's the whole vocabulary you need to start reading R code: <strong>code</strong> is what you type, <strong>comments</strong> are notes for humans, <strong>functions</strong> are named procedures called with parentheses, and <strong>operators</strong> are shortcut symbols.</p>
</section>
<!-- ============================================ -->
<!-- SECTION 3 — Variables -->
<!-- ============================================ -->
<section id="section-3" class="chapter">
<div class="chapter-header">
<span class="chapter-number">Chapter 03</span>
<h2 class="chapter-title">Variable Assignment: Storing Values</h2>
</div>
<p>A <strong>variable</strong> is a named container that holds a value. Once you store something in a variable, you can refer to it by name in later calculations. This saves typing and makes your code easier to read.</p>
<p>In R, we assign values using the arrow operator <code><-</code> or the equals sign <code>=</code>. Read it as "gets":</p>
<div class="code-cell" data-cell-id="cell-3-1">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor"># Store a measurement of stream discharge (in cubic meters per second)
discharge_cms <- 2.34
# Store a stream name (text values go in quotes)
stream_name <- "Bear Creek"
# Store a count of macroinvertebrate taxa observed
taxa_richness = 23
# To see what's in a variable, just type its name
discharge_cms
stream_name
taxa_richness</textarea>
<div class="code-output" data-output></div>
</div>
<p>You can use variables in calculations:</p>
<div class="code-cell" data-cell-id="cell-3-2">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor"># From the previous cell
discharge_cms <- 2.34
# Convert that discharge from cubic meters per second to cubic feet per second
# (1 cms = 35.3147 cfs)
discharge_cfs <- discharge_cms * 35.3147
discharge_cfs</textarea>
<div class="code-output" data-output></div>
</div>
<h3>Naming rules</h3>
<p>Variable names should be descriptive. <code>nitrate_mg_per_L</code> is far better than <code>x</code> because anyone reading your code (including future-you) will know what it means. A few rules:</p>
<ul>
<li>Names can contain letters, numbers, dots, and underscores</li>
<li>Names must start with a letter</li>
<li>R is case-sensitive: <code>Discharge</code> and <code>discharge</code> are different variables</li>
<li>Avoid using names of built-in functions like <code>mean</code>, <code>sum</code>, or <code>c</code></li>
</ul>
<!-- Exercise 3.1 -->
<div class="exercise" data-exercise-id="ex-3-1">
<div class="exercise-header">
<span class="exercise-tag">Exercise 3.1</span>
<span class="exercise-meta">Velocity-area discharge</span>
</div>
<div class="exercise-prompt">
<p>A stream's cross-section has a measured width of 4.2 meters and an average depth of 0.35 meters. The mean current velocity is 0.68 meters per second. Create three variables to store these values, then compute discharge using the velocity-area method:</p>
<p class="equation">Q = w × d × v</p>
<p>where Q is discharge (m³/s), w is width (m), d is mean depth (m), and v is mean velocity (m/s). Store the answer in a variable called <code>discharge</code> and print it.</p>
</div>
<div class="code-cell exercise-cell" data-cell-id="ex-3-1-attempt" data-assess="ex-3-1">
<div class="code-cell-header">
<span class="code-cell-label">Your answer</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor" placeholder="# Write your code here…"></textarea>
<div class="code-output" data-output></div>
</div>
<details class="solution">
<summary><span class="solution-toggle">Reveal solution</span></summary>
<div class="solution-body">
<div class="code-cell" data-cell-id="ex-3-1-sol">
<div class="code-cell-header">
<span class="code-cell-label">R · Solution</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">width_m <- 4.2
depth_m <- 0.35
velocity_ms <- 0.68
discharge <- width_m * depth_m * velocity_ms
discharge</textarea>
<div class="code-output" data-output></div>
</div>
<p class="explanation"><strong>Explanation.</strong> We stored each measurement in a clearly named variable, then translated the equation directly. The velocity-area method is the most basic field technique for measuring stream discharge, and it's the foundation for more sophisticated methods you'll encounter later (like the midsection method that integrates across multiple verticals). A discharge of about 1 m³/s indicates a small to mid-sized headwater stream.</p>
</div>
</details>
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 4 — Vectors -->
<!-- ============================================ -->
<section id="section-4" class="chapter">
<div class="chapter-header">
<span class="chapter-number">Chapter 04</span>
<h2 class="chapter-title">Vectors: Lists of Values</h2>
</div>
<p>In watershed ecology, you almost never make just one measurement — you sample across sites, dates, or depths. A <strong>vector</strong> is an ordered list of values of the same type (all numbers, or all text). You build vectors with the <code>c()</code> function, which stands for "combine."</p>
<div class="code-cell" data-cell-id="cell-4-1">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor"># Daily mean discharge (m³/s) over a week
weekly_q <- c(2.1, 2.4, 8.7, 5.3, 3.2, 2.6, 2.3)
weekly_q
# Dissolved oxygen readings (mg/L) at 8 sites along a stream
do_mg_L <- c(9.2, 8.8, 7.5, 6.1, 5.8, 7.2, 8.4, 9.0)
# Site names from a watershed survey
site_names <- c("Headwater", "Trib_A", "Below_Trib_A", "Mid_reach", "Pasture", "Forest_in")
site_names</textarea>
<div class="code-output" data-output></div>
</div>
<h3>Math on vectors</h3>
<p>R applies math operations to every element of a vector at once. This is called <strong>vectorization</strong>, and it's one of the most powerful features of R:</p>
<div class="code-cell" data-cell-id="cell-4-2">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor"># From the previous cell
do_mg_L <- c(9.2, 8.8, 7.5, 6.1, 5.8, 7.2, 8.4, 9.0)
# Convert all DO readings from mg/L to micrograms per liter
do_mg_L * 1000
# Summary statistics for the DO data
mean(do_mg_L)
median(do_mg_L)
min(do_mg_L)
max(do_mg_L)
sd(do_mg_L)
length(do_mg_L)</textarea>
<div class="code-output" data-output></div>
</div>
<div class="aside-note">
<strong>⚠ Watch out:</strong> <code>length()</code> here means the number of items in the vector. R uses the word in the general sense.
</div>
<h3>Pulling out specific values</h3>
<p>Use square brackets <code>[ ]</code> to access individual elements. R indexes from 1 (not 0):</p>
<div class="code-cell" data-cell-id="cell-4-3">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">weekly_q <- c(2.1, 2.4, 8.7, 5.3, 3.2, 2.6, 2.3)
# The first day's discharge
weekly_q[1]
# The third day's discharge — note the storm pulse!
weekly_q[3]
# Days 2 through 4 (covering the storm and immediate recession)
weekly_q[2:4]
# Just days 1, 4, and 7
weekly_q[c(1, 4, 7)]</textarea>
<div class="code-output" data-output></div>
</div>
<p>You can also pull out values that meet a condition. This is called <strong>logical subsetting</strong>:</p>
<div class="code-cell" data-cell-id="cell-4-4">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">do_mg_L <- c(9.2, 8.8, 7.5, 6.1, 5.8, 7.2, 8.4, 9.0)
# Which sites had DO below 6 mg/L (a common stress threshold for many fish)?
do_mg_L < 6
# Pull out only the readings below 6 mg/L
do_mg_L[do_mg_L < 6]</textarea>
<div class="code-output" data-output></div>
</div>
<!-- Exercise 4.1 -->
<div class="exercise" data-exercise-id="ex-4-1">
<div class="exercise-header">
<span class="exercise-tag">Exercise 4.1</span>
<span class="exercise-meta">Nitrate monitoring</span>
</div>
<div class="exercise-prompt">
<p>You measured nitrate concentrations (mg N/L) at 10 sites across an agricultural watershed: 0.42, 1.85, 0.31, 2.94, 1.12, 0.58, 3.21, 0.27, 2.05, 1.43.</p>
<ol class="exercise-steps">
<li>Store these in a vector called <code>nitrate</code>.</li>
<li>Store the mean in <code>nitrate_mean</code> and the standard deviation in <code>nitrate_sd</code>.</li>
<li>The EPA recommends a threshold of 1.0 mg/L for ecologically meaningful nitrate enrichment. Store the number of sites exceeding this threshold in <code>n_high</code>.</li>
</ol>
</div>
<div class="code-cell exercise-cell" data-cell-id="ex-4-1-attempt" data-assess="ex-4-1">
<div class="code-cell-header">
<span class="code-cell-label">Your answer</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor" placeholder="# Write your code here…"></textarea>
<div class="code-output" data-output></div>
</div>
<details class="solution">
<summary><span class="solution-toggle">Reveal solution</span></summary>
<div class="solution-body">
<div class="code-cell" data-cell-id="ex-4-1-sol">
<div class="code-cell-header">
<span class="code-cell-label">R · Solution</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor"># (a)
nitrate <- c(0.42, 1.85, 0.31, 2.94, 1.12, 0.58, 3.21, 0.27, 2.05, 1.43)
# (b)
nitrate_mean <- mean(nitrate)
nitrate_sd <- sd(nitrate)
nitrate_mean
nitrate_sd
# (c)
n_high <- sum(nitrate > 1.0)
n_high</textarea>
<div class="code-output" data-output></div>
</div>
<p class="explanation"><strong>Explanation.</strong> Part (c) uses a clever trick. The expression <code>nitrate > 1.0</code> returns a vector of TRUE/FALSE values — one for each site. When you call <code>sum()</code> on logical values, R counts the TRUEs. So <code>sum(nitrate > 1.0)</code> is just "how many sites exceeded the threshold?" You'll use this pattern constantly when screening monitoring data against water quality criteria.</p>
</div>
</details>
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 5 — Data Frames -->
<!-- ============================================ -->
<section id="section-5" class="chapter">
<div class="chapter-header">
<span class="chapter-number">Chapter 05</span>
<h2 class="chapter-title">Data Frames: The R Spreadsheet</h2>
</div>
<p>A <strong>data frame</strong> is R's version of a spreadsheet. It has rows (typically one per sample, site, or sampling date) and columns (one per measurement or variable). Data frames are the workhorse of data analysis.</p>
<p>Let's build a small data frame from a hypothetical synoptic stream survey:</p>
<div class="code-cell" data-cell-id="cell-5-1">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">stream_data <- data.frame(
site_id = 1:10,
land_use = c("Forest", "Forest", "Pasture", "Pasture", "Urban",
"Urban", "Forest", "Pasture", "Urban", "Forest"),
temp_C = c(11.2, 10.8, 14.6, 15.3, 18.7, 19.4, 11.5, 14.9, 17.8, 10.5),
do_mg_L = c(9.5, 9.7, 7.8, 7.2, 5.9, 5.5, 9.4, 7.5, 6.1, 9.8),
nitrate_mgL = c(0.15, 0.18, 1.45, 1.82, 2.35, 2.61, 0.21, 1.67, 2.14, 0.13),
ept_taxa = c(18, 17, 9, 8, 4, 3, 19, 7, 5, 20)
)
stream_data</textarea>
<div class="code-output" data-output></div>
</div>
<p>The <code>ept_taxa</code> column counts the number of Ephemeroptera, Plecoptera, and Trichoptera (mayfly, stonefly, and caddisfly) taxa — a common bioindicator where higher numbers generally suggest better water quality.</p>
<h3>Inspecting a data frame</h3>
<p>Real datasets often have hundreds or thousands of rows, so you usually want a quick look rather than the whole thing:</p>
<div class="code-cell" data-cell-id="cell-5-2">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">stream_data <- data.frame(
site_id = 1:10,
land_use = c("Forest", "Forest", "Pasture", "Pasture", "Urban",
"Urban", "Forest", "Pasture", "Urban", "Forest"),
temp_C = c(11.2, 10.8, 14.6, 15.3, 18.7, 19.4, 11.5, 14.9, 17.8, 10.5),
do_mg_L = c(9.5, 9.7, 7.8, 7.2, 5.9, 5.5, 9.4, 7.5, 6.1, 9.8),
nitrate_mgL = c(0.15, 0.18, 1.45, 1.82, 2.35, 2.61, 0.21, 1.67, 2.14, 0.13),
ept_taxa = c(18, 17, 9, 8, 4, 3, 19, 7, 5, 20)
)
head(stream_data)
tail(stream_data, 3)
str(stream_data)
nrow(stream_data)
ncol(stream_data)</textarea>
<div class="code-output" data-output></div>
</div>
<h3>Accessing columns and filtering rows</h3>
<p>Use the dollar sign <code>$</code> to grab a single column:</p>
<div class="code-cell" data-cell-id="cell-5-3">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">stream_data <- data.frame(
site_id = 1:10,
land_use = c("Forest", "Forest", "Pasture", "Pasture", "Urban",
"Urban", "Forest", "Pasture", "Urban", "Forest"),
temp_C = c(11.2, 10.8, 14.6, 15.3, 18.7, 19.4, 11.5, 14.9, 17.8, 10.5),
do_mg_L = c(9.5, 9.7, 7.8, 7.2, 5.9, 5.5, 9.4, 7.5, 6.1, 9.8),
nitrate_mgL = c(0.15, 0.18, 1.45, 1.82, 2.35, 2.61, 0.21, 1.67, 2.14, 0.13),
ept_taxa = c(18, 17, 9, 8, 4, 3, 19, 7, 5, 20)
)
# All the temperatures
stream_data$temp_C
# Average nitrate across all sites
mean(stream_data$nitrate_mgL)
# All forest sites
stream_data[stream_data$land_use == "Forest", ]
# Urban sites with nitrate above 2 mg/L
stream_data[stream_data$land_use == "Urban" & stream_data$nitrate_mgL > 2, ]</textarea>
<div class="code-output" data-output></div>
</div>
<p>The <code>&</code> symbol means "AND" (both conditions must be true). The <code>|</code> symbol means "OR" (either can be true).</p>
<!-- Exercise 5.1 -->
<div class="exercise" data-exercise-id="ex-5-1">
<div class="exercise-header">
<span class="exercise-tag">Exercise 5.1</span>
<span class="exercise-meta">Subsetting a survey</span>
</div>
<div class="exercise-prompt">
<p>Using the <code>stream_data</code> data frame from the example above (you'll need to recreate it in your answer cell — code persists between runs in the same cell, but each cell starts fresh):</p>
<ol class="exercise-steps">
<li>Store the average EPT richness at the forested sites in <code>forest_ept_mean</code>.</li>
<li>Store the count of urban sites in <code>n_urban</code>.</li>
<li>Store a data frame of sites with temperature below 15°C in <code>cool_sites</code>.</li>
</ol>
</div>
<div class="code-cell exercise-cell" data-cell-id="ex-5-1-attempt" data-assess="ex-5-1">
<div class="code-cell-header">
<span class="code-cell-label">Your answer</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor" placeholder="# Recreate stream_data here, then write your answer…
stream_data <- data.frame(
site_id = 1:10,
land_use = c('Forest', 'Forest', 'Pasture', 'Pasture', 'Urban',
'Urban', 'Forest', 'Pasture', 'Urban', 'Forest'),
temp_C = c(11.2, 10.8, 14.6, 15.3, 18.7, 19.4, 11.5, 14.9, 17.8, 10.5),
do_mg_L = c(9.5, 9.7, 7.8, 7.2, 5.9, 5.5, 9.4, 7.5, 6.1, 9.8),
nitrate_mgL = c(0.15, 0.18, 1.45, 1.82, 2.35, 2.61, 0.21, 1.67, 2.14, 0.13),
ept_taxa = c(18, 17, 9, 8, 4, 3, 19, 7, 5, 20)
)
# Your code below…
"></textarea>
<div class="code-output" data-output></div>
</div>
<details class="solution">
<summary><span class="solution-toggle">Reveal solution</span></summary>
<div class="solution-body">
<div class="code-cell" data-cell-id="ex-5-1-sol">
<div class="code-cell-header">
<span class="code-cell-label">R · Solution</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">stream_data <- data.frame(
site_id = 1:10,
land_use = c("Forest", "Forest", "Pasture", "Pasture", "Urban",
"Urban", "Forest", "Pasture", "Urban", "Forest"),
temp_C = c(11.2, 10.8, 14.6, 15.3, 18.7, 19.4, 11.5, 14.9, 17.8, 10.5),
do_mg_L = c(9.5, 9.7, 7.8, 7.2, 5.9, 5.5, 9.4, 7.5, 6.1, 9.8),
nitrate_mgL = c(0.15, 0.18, 1.45, 1.82, 2.35, 2.61, 0.21, 1.67, 2.14, 0.13),
ept_taxa = c(18, 17, 9, 8, 4, 3, 19, 7, 5, 20)
)
# (a)
forest_ept_mean <- mean(stream_data$ept_taxa[stream_data$land_use == "Forest"])
forest_ept_mean
# (b)
n_urban <- sum(stream_data$land_use == "Urban")
n_urban
# (c)
cool_sites <- stream_data[stream_data$temp_C < 15, ]
cool_sites</textarea>
<div class="code-output" data-output></div>
</div>
<p class="explanation"><strong>Explanation.</strong> In part (a), the inner part <code>stream_data$land_use == "Forest"</code> gives us a TRUE/FALSE vector marking which rows are forest sites. We use that to subset <code>stream_data$ept_taxa</code>, keeping only the EPT counts from forest sites. Reading from the inside out is a useful habit when code looks complicated. Notice the dramatic difference: forest sites average around 18 EPT taxa, while the urban sites average around 4 — exactly the pattern bioassessment programs are designed to detect.</p>
</div>
</details>
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 6 — Operators -->
<!-- ============================================ -->
<section id="section-6" class="chapter">
<div class="chapter-header">
<span class="chapter-number">Chapter 06</span>
<h2 class="chapter-title">Operators: R's Vocabulary</h2>
</div>
<h3>Arithmetic operators</h3>
<div class="code-cell" data-cell-id="cell-6-1">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">10 + 3 # addition
10 - 3 # subtraction
10 * 3 # multiplication
10 / 3 # division
10 ^ 2 # exponent (10 squared)</textarea>
<div class="code-output" data-output></div>
</div>
<h3>Comparison operators</h3>
<p>These return TRUE or FALSE:</p>
<div class="code-cell" data-cell-id="cell-6-2">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">5 > 3
5 < 3
5 == 5 # equal to (note the DOUBLE equals!)
5 != 4 # not equal to
5 >= 5
5 <= 4</textarea>
<div class="code-output" data-output></div>
</div>
<div class="aside-note aside-warn">
<strong>The <code>=</code> vs <code>==</code> trap.</strong> Remember that a single <code>=</code> assigns a value (Chapter 03)!
</div>
<h3>Logical operators</h3>
<div class="code-cell" data-cell-id="cell-6-3">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">TRUE & FALSE # AND: both must be TRUE
TRUE | FALSE # OR: at least one must be TRUE
!TRUE # NOT: flips TRUE to FALSE</textarea>
<div class="code-output" data-output></div>
</div>
<!-- Exercise 6.1 -->
<div class="exercise" data-exercise-id="ex-6-1">
<div class="exercise-header">
<span class="exercise-tag">Exercise 6.1</span>
<span class="exercise-meta">Compliance check</span>
</div>
<div class="exercise-prompt">
<p>You're screening a stream site for compliance with two water quality criteria: DO must be at least 6.0 mg/L AND temperature must be below 20°C for it to be considered suitable habitat for a sensitive coldwater species. Given the measurements below, write a single line of code that stores <code>TRUE</code> in a variable called <code>is_suitable</code> if the site meets both criteria, and <code>FALSE</code> otherwise.</p>
</div>
<div class="code-cell exercise-cell" data-cell-id="ex-6-1-attempt" data-assess="ex-6-1">
<div class="code-cell-header">
<span class="code-cell-label">Your answer</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">site_do <- 7.4
site_temp <- 17.8
# Your one-line answer below:
</textarea>
<div class="code-output" data-output></div>
</div>
<details class="solution">
<summary><span class="solution-toggle">Reveal solution</span></summary>
<div class="solution-body">
<div class="code-cell" data-cell-id="ex-6-1-sol">
<div class="code-cell-header">
<span class="code-cell-label">R · Solution</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">site_do <- 7.4
site_temp <- 17.8
is_suitable <- site_do >= 6.0 & site_temp < 20
is_suitable</textarea>
<div class="code-output" data-output></div>
</div>
<p class="explanation"><strong>Explanation.</strong> A two-part water quality criterion translates directly to a logical AND. Both parts have to be true: DO at or above the minimum AND temperature below the maximum. Try changing <code>site_do</code> to 4.5, then <code>site_temp</code> to 22, and re-running to see how the result changes. This same logic pattern scales directly to filtering whole datasets — same <code>&</code>, same <code>==</code>, just applied to columns instead of single values.</p>
</div>
</details>
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 7 — Equations -->
<!-- ============================================ -->
<section id="section-7" class="chapter">
<div class="chapter-header">
<span class="chapter-number">Chapter 07</span>
<h2 class="chapter-title">Translating Equations into Code</h2>
</div>
<p>Watershed ecology is full of equations — runoff models, nutrient load calculations, dilution equations, hydraulic geometry relationships. A core R skill is taking an equation off a textbook page and turning it into working code.</p>
<h3>Manning's equation for open-channel flow</h3>
<p class="equation-block">v = (1/n) · R<sup>2/3</sup> · S<sup>1/2</sup></p>
<p>where v is mean velocity (m/s), n is Manning's roughness coefficient, R is hydraulic radius (m), and S is the channel slope (m/m).</p>
<div class="code-cell" data-cell-id="cell-7-1">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor"># Parameters for a small cobble-bedded stream
n <- 0.045 # Manning's n for cobble/boulder channel
R <- 0.28 # hydraulic radius (m)
S <- 0.012 # slope (m/m)
v <- (1/n) * R^(2/3) * S^(1/2)
v</textarea>
<div class="code-output" data-output></div>
</div>
<h3>Pollutant load calculation</h3>
<p class="equation-block">L = C × Q × k</p>
<p>where L is load (kg/day), C is concentration (mg/L), Q is discharge (m³/s), and k is the unit conversion factor 86.4.</p>
<div class="code-cell" data-cell-id="cell-7-2">
<div class="code-cell-header">
<span class="code-cell-label">R</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">nitrate_conc <- 1.85 # mg/L
discharge <- 4.2 # m³/s
k <- 86.4 # unit conversion
nitrate_load <- nitrate_conc * discharge * k
nitrate_load # kg N per day</textarea>
<div class="code-output" data-output></div>
</div>
<div class="aside-note">
<strong>Tip:</strong> When an equation has nested operations, build it up from the inside. Follow PEMDAS and use parentheses generously!
</div>
<!-- Exercise 7.1 -->
<div class="exercise" data-exercise-id="ex-7-1">
<div class="exercise-header">
<span class="exercise-tag">Exercise 7.1</span>
<span class="exercise-meta">Streeter-Phelps</span>
</div>
<div class="exercise-prompt">
<p>The Streeter-Phelps deficit equation describes how dissolved oxygen recovers downstream of a pollution source. A simplified version for the DO deficit at a given travel time is:</p>
<p class="equation-block">D<sub>t</sub> = D<sub>0</sub> · e<sup>−k₂t</sup></p>
<p>where D<sub>0</sub> is the initial DO deficit (mg/L), k₂ is the reaeration rate constant (per day), and t is travel time (days). In R, <code>exp(x)</code> computes e raised to the power of x.</p>
<p>A point source produces an initial DO deficit of 4.5 mg/L. The stream has a reaeration rate of 0.35 per day. Compute the DO deficit 3 days downstream and store the result in a variable called <code>Dt</code>.</p>
</div>
<div class="code-cell exercise-cell" data-cell-id="ex-7-1-attempt" data-assess="ex-7-1">
<div class="code-cell-header">
<span class="code-cell-label">Your answer</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor" placeholder="# Write your code here…"></textarea>
<div class="code-output" data-output></div>
</div>
<details class="solution">
<summary><span class="solution-toggle">Reveal solution</span></summary>
<div class="solution-body">
<div class="code-cell" data-cell-id="ex-7-1-sol">
<div class="code-cell-header">
<span class="code-cell-label">R · Solution</span>
<button class="run-btn">Run</button>
</div>
<textarea class="code-editor">D0 <- 4.5
k2 <- 0.35
t <- 3
Dt <- D0 * exp(-k2 * t)
Dt</textarea>
<div class="code-output" data-output></div>
</div>
<p class="explanation"><strong>Explanation.</strong> This is a classic textbook calculation in stream chemistry. The result (~1.58 mg/L) means the deficit has decayed substantially — about two-thirds of the way back toward saturation — over those three days. Storing inputs as named variables (rather than typing the numbers directly into the equation) makes it trivial to recalculate D<sub>t</sub> for a different travel time or reaeration rate. This is also the foundation of the more complete Streeter-Phelps model that you'll see in water quality modeling courses.</p>
</div>
</details>
</div>
</section>
<!-- ============================================ -->
<!-- SECTION 8 — Column Math -->
<!-- ============================================ -->
<section id="section-8" class="chapter">
<div class="chapter-header">
<span class="chapter-number">Chapter 08</span>
<h2 class="chapter-title">Calculations Across Data Frame Columns</h2>
</div>
<p>Because columns are vectors, you can do math across an entire column in one line — no loops needed. R automatically applies the operation row by row.</p>
<div class="code-cell" data-cell-id="cell-8-1">
<div class="code-cell-header">
<span class="code-cell-label">R</span>