2 Chapter 2 — Getting Set Up with R
Applied Epidemiology in Aquaculture — Part I: Foundations
Where this sits — Foundations. Setting up R is the groundwork for every phase of the framework (Anticipate → Prevent → Detect → Respond → Safeguard); the tools here are used in all of them.
2.1 Overview
In Chapter 1 we did one small calculation by hand. That was fine for three numbers. But a real farm generates thousands of them — weekly mortalities across dozens of cages, lab results, temperatures, treatments — and a calculator (or a sprawling spreadsheet with a formula you can no longer remember) stops being trustworthy. R is how we take control of that data: it is free, it runs the same on every computer, and — most importantly — it keeps a written record of exactly what you did, so your analysis can be checked, corrected, and repeated next season.
This chapter takes you from nothing installed to a working setup, teaches just enough R to be dangerous, and ends with you importing the dataset that the rest of the book is built on. By the end you will be able to install and open R, understand the four parts of the RStudio screen, create objects and run functions, load packages the modern way, and import and take a first look at a real farm dataset.
Everything here uses one file, aquafarms_register.csv — a one-month health snapshot of our three farms: Aysén Salmon Co., Lago Verde Tilapia, and Camarones del Golfo (shrimp). We will meet it properly at the end of the chapter.
No prior coding experience is assumed. If you have never written a line of code, you are in exactly the right place.
2.2 2.1 Preparation
2.2.1 Install R and RStudio
You need two free programs, installed in this order:
- R — the engine that does the computing. Download it from the Comprehensive R Archive Network, cran.r-project.org, choosing the version for your operating system (Windows, macOS, or Linux) and running the installer with the default options.
- RStudio Desktop — a friendly workbench that sits on top of R and makes it far nicer to use. Download the free version from posit.co/download/rstudio-desktop and install it.
Install R first, then RStudio: RStudio looks for R on your computer when it starts. From now on you open RStudio (not R) whenever you want to work.
2.2.2 Meet RStudio — the four panes
When RStudio opens you will see the screen divided into panes. Four of them matter:
- Source editor (top-left) — where you write and save your R scripts (files of code ending in
.R). This is where real work lives, because a script is a record you can re-run. - Console (bottom-left) — where code actually runs and prints results. You can type here directly for quick throwaway calculations.
- Environment (top-right) — a list of the objects (data, values) you have created this session.
- Files / Plots / Help (bottom-right) — your folders, any graphs you make, and R’s built-in help pages.
The golden habit: write code in the Source editor, not the Console. To run a line from the editor, put the cursor on it and press Ctrl + Enter (Windows) or Cmd + Enter (Mac). The line is sent to the Console and runs.
2.2.3 Start an RStudio Project
Before writing any code, create a Project — a self-contained folder for the book. In RStudio: File → New Project → New Directory → New Project, name it something like fish-epi-book, and choose where to put it.
Why bother? Because a Project fixes your working directory — the folder R treats as “here”. That means you can refer to your data file as simply data/aquafarms_register.csv instead of a long, fragile path like C:/Users/Fernando/Desktop/.../data/... that breaks the moment you move the folder or open it on another computer. We make this robust with the here package, below.
2.2.4 The folder layout
Inside your project folder, make two subfolders so things stay tidy (you can create them in the Files pane with New Folder):
fish-epi-book/
├── fish-epi-book.Rproj <- the Project file (already created)
├── data/ <- put aquafarms_register.csv here
└── scripts/ <- put make_aquafarms_register.R here
Drop the provided aquafarms_register.csv into data/. (The script make_aquafarms_register.R that produced it is in scripts/, for the curious — you never need to run it, but it shows exactly how the data were simulated.)
2.2.5 Load the book’s package stack
R comes with a lot built in, but its real power is in packages — add-ons that other people have written. You install a package once (it downloads from the internet), then load it in each session you want to use it.
Most books make you type install.packages() and library() over and over. We will use a tidier approach that this whole book follows: the pacman package and its one-stop function p_load(), which installs a package if it is missing and then loads it. Install pacman once:
install.packages("pacman") # run this one time onlyThen, at the top of every script in this book, load the tools you need in a single line:
pacman::p_load(
rio, # importing and exporting data of any type
here, # building safe file paths from the project root
tidyverse, # the core toolkit for data wrangling and plotting
janitor # cleaning data and quick summary tables
)The first time you run this it may take a few minutes as packages download; after that it is instant. The :: in pacman::p_load simply means “use the p_load function from the pacman package” — a handy way to call a function without loading its whole package first.
These four are our spine. Later chapters add specialised packages (for diagnostic tests, survival analysis, mapping, and so on), but
rio,here,tidyverse, andjanitorappear in almost every chapter.
2.3 2.2 R fundamentals in fifteen minutes
2.3.1 R as a calculator
Type this in a script and run it; the answer appears in the Console:
5 + 3 # 8
2600 / 48 # 54.1667 (e.g. a mortality count per sampled fish — not yet meaningful)
sqrt(144) # 12Anything after a # is a comment — R ignores it. Comments are notes to your future self; use them generously.
2.3.2 Objects and the assignment arrow
The heart of R is storing a value under a name so you can reuse it. You do this with the assignment arrow <- (type it as a less-than sign and a dash; the keyboard shortcut is Alt + -):
sampled <- 48 # fish examined in one cage
positive <- 8 # of those, number positive for SRS
prevalence <- positive / sampled * 100
prevalence # 16.66667The name prevalence now holds the value and appears in your Environment pane. Change positive and re-run, and prevalence updates — this is how analyses stay consistent.
2.3.3 Vectors and data types
A vector is a sequence of values of the same type, built with c() (“combine”):
temps <- c(12.1, 13.6, 12.3, 12.3, 11.2) # water temperature in five salmon cages
mean(temps) # 12.3
max(temps) # 13.6
length(temps) # 5R works on the whole vector at once — no loops needed:
temps_f <- temps * 9/5 + 32 # convert all five to Fahrenheit in one stepValues come in a few basic types, and knowing them prevents most beginner confusion:
- numeric — numbers, e.g.
12.1,38020 - character — text, always in quotes, e.g.
"Atlantic salmon" - logical —
TRUEorFALSE, often produced by comparisons (temps > 13) - factor — a category with a fixed set of levels (e.g. species); important later for models and plots
2.3.4 Functions
A function takes inputs (its arguments, inside the parentheses) and returns a result. You have already used several: mean(), sqrt(), c(). The pattern is always functionname(argument1, argument2, ...):
round(16.66667, digits = 1) # 16.7When you are unsure what a function does or what arguments it takes, ask R: type ?mean (or ?round) and the help page opens in the bottom-right pane.
When something goes wrong — the three beginner classics. (1)
could not find function "p_load"usually means a package isn’t loaded — run yourpacman::p_load(...)line. (2)object 'prevalance' not foundis almost always a typo or a name you haven’t created yet (note the misspelling). (3) A+sitting in the Console instead of>means R is waiting for you to finish an incomplete command — you probably have an unclosed(or". PressEscto cancel and try again. Errors are normal and not harmful; read them literally.
2.4 2.3 Bringing in the farm data
2.4.1 Import the dataset
With your project open and aquafarms_register.csv sitting in data/, this is the whole import:
register <- import(here("data", "aquafarms_register.csv"))Two ideas in one line. here("data", "aquafarms_register.csv") builds the correct path to the file starting from your project folder, so it works on any computer. import() (from rio) reads the file — rio recognises the .csv and dozens of other formats automatically, so you use the same function whether the file is a CSV, Excel, or something else.
2.4.2 Take a first look
Never analyse data you haven’t eyeballed. A handful of functions tell you what you’re holding:
dim(register) # 24 12 -> 24 rows, 12 columns
names(register) # the column names
head(register) # the first six rowsFor a compact, typed overview, glimpse() (from the tidyverse) is the one to reach for. It lists every column, its type, and the first few values:
glimpse(register)
#> Rows: 24
#> Columns: 12
#> $ farm <chr> "Aysen Salmon Co.", "Aysen Salmon Co.", ...
#> $ species <chr> "Atlantic salmon", "Atlantic salmon", ...
#> $ system <chr> "sea cage", "sea cage", ...
#> $ unit_id <chr> "AYS-01", "AYS-02", "AYS-03", ...
#> $ water_temp_c <dbl> 12.1, 13.6, 12.3, 12.3, 11.2, ...
#> $ n_stocked <int> 38020, 28704, 34184, 27341, 28628, ...
#> $ ...And summary() gives the range and averages of every column at once — a fast way to spot impossible values (a negative count, a 90 °C pond) that signal a data-entry error.
summary(register)2.4.3 A first grouped summary
Two small steps show the kind of thing you’ll do constantly. First, a clean frequency table of species with janitor’s tabyl():
tabyl(register, species)
#> species n percent
#> Atlantic salmon 8 0.3333333
#> Nile tilapia 8 0.3333333
#> Whiteleg shrimp 8 0.3333333Eight production units per farm, evenly balanced. Second, the average water temperature by species, our first taste of the tidyverse “pipe” (|>), which reads left-to-right as “take the data, then group it, then summarise it”:
register |>
group_by(species) |>
summarise(mean_temp = mean(water_temp_c))
#> species mean_temp
#> Atlantic salmon 12.3
#> Nile tilapia 27.5
#> Whiteleg shrimp 29.62.5 2.4 Interpretation on the farm
That last table is tiny but it already tells a real epidemiological story. The three species live in completely different thermal worlds — salmon at around 12 °C, tilapia at 27.5 °C, shrimp at nearly 30 °C. Hold that thought, because temperature is one of the strongest drivers of disease we will meet: it governs when Streptococcus flares in tilapia, how fast AHPND crashes a shrimp pond, and the seasonality of SRS in salmon. The same column that looks like boring metadata is, in epidemiology, a key environmental arm of the triad from Chapter 1.
Look too at n_stocked in your summary() output: a shrimp pond holds hundreds of thousands of animals while a salmon cage holds tens of thousands. That is why, across all 24 units, the month’s mortality count is dominated by shrimp — and it is a first reminder of Chapter 1’s lesson about denominators. We will turn these raw counts into proper, comparable measures of disease in Chapter 4.
2.6 2.5 Exercises
Try it yourself (2.1). In a fresh script, load the package stack, import
register, and runglimpse()on it. How many columns are of type character, and how many are numeric?
2.2 Create a vector of the five salmon temperatures from the chapter and compute their mean and standard deviation (sd()). Then convert the vector to Fahrenheit.
2.3 Using the register, write one line that makes a tabyl() of the system column. Which system appears most often, and why does that make sense given the farms?
2.4 The prevalence of a disease in a unit is n_positive / n_sampled * 100. Pick any row from head(register) and calculate its prevalence by hand (or in the Console), the way we did for AYS-01 (8 of 48 positive → 16.7%).
2.5 Deliberately create an error: type mean(temp) when your vector is called temps. Read the error message. What is R telling you, and how do you fix it? (Getting comfortable with errors now will save you hours later.)
2.7 Summary & what’s next
- You installed R (the engine) and RStudio (the workbench), in that order.
- You learned the four RStudio panes and the habit of writing code in scripts, not the Console.
- An RStudio Project plus the
herepackage make file paths robust across computers. - You load tools in one line with
pacman::p_load(...); our spine isrio,here,tidyverse,janitor. - You met R’s building blocks — objects (
<-), vectors (c()), data types, and functions — and the three classic beginner errors. - You imported the book’s dataset with
import(here(...))and inspected it withdim(),glimpse(),summary(), andtabyl().
You now have a working lab and a dataset in hand. In Chapter 3 — Describing What You See, we use this same register to learn the descriptive statistics a fish health specialist actually relies on: variable types, means versus medians, measuring spread, distributions, and the first proper plots — the groundwork for every measure of disease that follows.
Files for this chapter: data/aquafarms_register.csv (the dataset) and scripts/make_aquafarms_register.R (the seeded generator, for transparency).