1 Day 1

Item Detail
Level Beginner — no prior R or coding experience assumed

1.1 Learning objectives

By the end of Day 1, each participant can:

  1. Explain why R is useful for epidemiology, and how R work differs from Excel, Stata or SAS.
  2. Describe “tidy data” and spot untidy layouts in a spreadsheet.
  3. Find their way around RStudio’s four panes and run code from a script.
  4. Use functions and arguments, and read a function’s help page.
  5. Install and load packages, and call a function with package::function().
  6. Create objects with <-, and check and convert their class.
  7. Build vectors and data frames, and pick out values with $ and [ ].
  8. Use math, comparison and logical operators, %in%, and handle missing values (NA).
  9. Chain steps together with the pipe (%>% or |>).
  10. Tell an error from a warning and fix common mistakes.

2 Why R for epidemiology?

R is a free, open-source programming language for statistics and graphics. For public-health work it offers:

  • Reproducibility — every step is written in a script, so anyone can rerun the analysis and get the same result.
  • Speed for repeated work — weekly surveillance reports can be regenerated with new data in seconds.
  • Breadth — thousands of free packages for data cleaning, epidemic curves, regression, mapping, dashboards and reports.
  • Community — large, active user communities and free resources such as the Epi R Handbook.

Key terms

Term Meaning
R The programming language and the engine that runs your code
RStudio The program (an IDE) you use to write and run R code more easily
Script A text file (.R) that stores your code so you can rerun and share it
Console Where R runs commands and prints results
Object Anything you store in R: a number, a dataset, a plot, a model
Function A command that takes inputs (arguments) and returns an output
Package A bundle of functions that someone has written and shared

2.1 Coming from Excel

Excel work often depends on memory and repetition: clicking, dragging, copying formulas. The steps are hidden, so errors are easy to make and hard to find. In R, every step is written in the script, so it can be viewed, edited, corrected and applied to new data.

Expect a short adjustment period — a couple of weeks of regular practice — before R feels comfortable.

Three mindset changes help most:

  1. Think in tidy data (next section).
  2. Functions are like Excel formulas — and, like formulas, they need exact syntax.
  3. Scripts replace clicking — like recording a macro, but readable and editable.

R and Excel can work together: R imports and exports Excel files easily (with packages such as rio and openxlsx).

2.2 Tidy data

R works best with data structured for machines, not for human eyes. Tidy data follows three rules:

  1. Each variable has its own column.
  2. Each observation has its own row.
  3. Each value has its own cell.

2.3 Coming from Stata or SAS

Task Stata SAS R
Comments *, //, /* */ *;, /* */ #
Code file do-file .sas program R script (.R)
Datasets in memory One at a time Many Many — each is an object
Working directory cd, pwd libname setwd(), getwd(), or here package
Import data use, import excel PROC IMPORT rio::import()
View data browse Explorer View()
Summarise summarize PROC SUMMARY summary(), skimr::skim()
New variable generate data step mutate()
Keep/drop variables keep, drop keep, drop select()
Filter rows keep if where, if filter()
Frequency table tab PROC FREQ table(), count(), janitor::tabyl()
Value labels label define formats factors

The rio package also imports Stata (.dta), SAS (.sas7bdat, .xpt) and SPSS (.sav, .por) files, so existing datasets can be brought straight into R.

3 RStudio tour

Open RStudio. It has four panes:

Pane Default position What it is for
Source Top left Writing and saving scripts
Console Bottom left Where code runs and results print
Environment / History Top right Objects you have created; past commands
Files / Plots / Packages / Help / Viewer Bottom right Browsing files, seeing plots, managing packages, reading help

Useful shortcuts

Action Windows Mac
Run current line or selection Ctrl + Enter Cmd + Return
Run whole script Ctrl + Shift + Enter Cmd + Shift + Return
Insert <- Alt + - Option + -
Insert pipe %>% Ctrl + Shift + M Cmd + Shift + M
Comment / uncomment lines Ctrl + Shift + C Cmd + Shift + C
Clear console Ctrl + L Ctrl + L

Recommended settings (Tools → Global Options → General): untick Restore .RData into workspace at startup and set Save workspace to .RData on exit to Never. This makes sure your script, not leftover objects, is the record of your work.

Try it: type 2 + 2 in the console and press Enter.

2 + 2
#> [1] 4

4 Scripts and comments

Always work in a script (File → New File → R Script), never only in the console. Save it as day1_basics.R.

Anything after # is a comment and is not run. Use comments to explain why, not just what.

# Day 1 — R basics
# Author: [your name]
# Purpose: practise objects, functions and operators

# Calculate the number of weeks in a 91-day reporting period
91 / 7
#> [1] 13

Style tips:

  • Use clear object names in snake_case (e.g. case_count, date_onset) — no spaces.
  • One step per line; put spaces around operators (x <- 5, not x<-5).
  • Organise long scripts with section headers: # Load packages ---- (RStudio turns these into a clickable outline).

5 Functions

A function takes inputs (arguments) and returns an output. Arguments go inside round brackets, separated by commas.

sqrt(49)                 # one argument
#> [1] 7
round(3.14159, digits = 2)   # two arguments, the second named
#> [1] 3.14
round(3.14159, 2)            # same result: arguments matched by position
#> [1] 3.14

Naming arguments makes code easier to read and avoids mistakes when the order is unclear.

ages <- c(23, 45, 31, NA, 52)
mean(ages)                 # NA because one value is missing
#> [1] NA
mean(ages, na.rm = TRUE)   # remove missing values first
#> [1] 37.75

Getting help: type ?mean or help(mean) in the console. A help page has Usage (the function and its arguments with defaults), Arguments (what each one means), Value (what is returned) and Examples (code you can copy and run).

6 Packages

A package is a collection of functions. Base R comes with many functions; packages add thousands more.

6.1 Install once, load every session

# Install from CRAN (only once per computer)
install.packages("tidyverse")
install.packages(c("rio", "here", "janitor"))

# Load into the current session (every time you start R)
library(tidyverse)
library(rio)

6.2 The pacman approach used in this course

pacman::p_load() installs a package if it is missing, then loads it — one line does both.

install.packages("pacman")   # once

pacman::p_load(
  rio,        # import and export
  here,       # file paths relative to the project
  tidyverse   # data management and visualisation
)

6.3 package::function()

The double colon calls a function from a package without loading the whole package, and makes clear where a function comes from.

rio::import("linelist.xlsx", which = "Sheet1")
dplyr::filter(linelist, age > 50)

Masked functions. When two loaded packages have a function with the same name, the one loaded last “masks” the other (R prints a message). For example, dplyr::filter() masks stats::filter(). Using package::function() avoids confusion.

Other package tasks: .libPaths() shows where packages are stored; update.packages() updates them; remove.packages("name") deletes one.

7 Objects

7.1 Everything is an object

You create an object with the assignment operator <- (“gets”). I totally discourage using = for assignment.

current_week <- "2018-W10"
current_week
#> [1] "2018-W10"
case_count <- 156
case_count * 2
#> [1] 312

Objects appear in the Environment pane. Assigning a new value to the same name overwrites it without warning.

7.2 Object classes

Every object has a class, which controls what you can do with it.

Class Example Notes
numeric 42, 3.7 Numbers (integers or decimals)
character "Lagos", "female" Text, always in quotes
logical TRUE, FALSE Results of comparisons
factor factor(c("low","high")) Categories with a set order of levels
Date as.Date("2026-11-30") Dates — allow date arithmetic
data.frame a table Rows = observations, columns = variables
class(156)
#> [1] "numeric"
class("Lagos")
#> [1] "character"
class(TRUE)
#> [1] "logical"
class(as.Date("2026-11-30"))
#> [1] "Date"

Converting classes — as.numeric(), as.character(), as.integer(), as.Date(), factor(). Testing classes — is.numeric(), is.character(), is.factor().

num_vector <- c(1, 2, 3, 4, 5)
class(num_vector)
#> [1] "numeric"
num_vector[3] <- "three"   # one text value turns the whole vector into character
num_vector
#> [1] "1"     "2"     "three" "4"     "5"
class(num_vector)
#> [1] "character"

Key lesson: a vector (and each data-frame column) holds one class only. A single text value in a numeric column turns the whole column into text — a very common cause of errors with data from Excel.

7.3 Vectors

A vector is a set of values of the same class, made with c() (“combine”).

districts <- c("Ikeja", "Surulere", "Uyo", "Eket", "Garki")
cases     <- c(34, 12, 27, 9, 41)

length(cases)
#> [1] 5
sum(cases)
#> [1] 123
mean(cases)
#> [1] 24.6
max(cases)
#> [1] 41

Useful shortcuts: 1:10 makes a sequence; seq(0, 100, by = 10) makes stepped sequences; rep("A", 3) repeats values.

7.4 Data frames

A data frame is a table: each column is a vector of equal length. This is the structure you will use for almost all epidemiological data.

linelist <- data.frame(
  case_id    = c("C001", "C002", "C003", "C004", "C005", "C006"),
  age        = c(23, 45, 31, NA, 52, 8),
  gender     = c("f", "m", "f", "m", "f", "m"),
  outcome    = c("Recover", "Death", "Recover", NA, "Death", "Recover"),
  wt_kg      = c(61, 80, 55, 72, 68, 25),
  ht_cm      = c(162, 175, 158, 170, 165, 128),
  date_onset = as.Date(c("2026-01-03", "2026-01-05", "2026-01-05",
                         "2026-01-08", "2026-01-10", "2026-01-12"))
)

linelist
#>   case_id age gender outcome wt_kg ht_cm date_onset
#> 1    C001  23      f Recover    61   162 2026-01-03
#> 2    C002  45      m   Death    80   175 2026-01-05
#> 3    C003  31      f Recover    55   158 2026-01-05
#> 4    C004  NA      m    <NA>    72   170 2026-01-08
#> 5    C005  52      f   Death    68   165 2026-01-10
#> 6    C006   8      m Recover    25   128 2026-01-12

Inspect a data frame:

nrow(linelist)      # number of rows
#> [1] 6
ncol(linelist)      # number of columns
#> [1] 7
names(linelist)     # column names
#> [1] "case_id"    "age"        "gender"     "outcome"    "wt_kg"     
#> [6] "ht_cm"      "date_onset"
str(linelist)       # structure: class of each column
#> 'data.frame':    6 obs. of  7 variables:
#>  $ case_id   : chr  "C001" "C002" "C003" "C004" ...
#>  $ age       : num  23 45 31 NA 52 8
#>  $ gender    : chr  "f" "m" "f" "m" ...
#>  $ outcome   : chr  "Recover" "Death" "Recover" NA ...
#>  $ wt_kg     : num  61 80 55 72 68 25
#>  $ ht_cm     : num  162 175 158 170 165 128
#>  $ date_onset: Date, format: "2026-01-03" "2026-01-05" ...
summary(linelist$age)
#>    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.     NAs 
#>     8.0    23.0    31.0    31.8    45.0    52.0       1

View(linelist) opens the data in a spreadsheet-like viewer (note the capital V).

7.5 Columns with $

$ selects one column from a data frame.

linelist$age
#> [1] 23 45 31 NA 52  8
class(linelist$gender)
#> [1] "character"
table(linelist$gender, linelist$outcome)   # cross-tabulation
#>    
#>     Death Recover
#>   f     1       2
#>   m     1       1

Create a new column (base R):

linelist$bmi <- linelist$wt_kg / (linelist$ht_cm / 100)^2
linelist[, c("case_id", "wt_kg", "ht_cm", "bmi")]
#>   case_id wt_kg ht_cm      bmi
#> 1    C001    61   162 23.24341
#> 2    C002    80   175 26.12245
#> 3    C003    55   158 22.03173
#> 4    C004    72   170 24.91349
#> 5    C005    68   165 24.97704
#> 6    C006    25   128 15.25879

7.6 Indexing with [ ]

For a vector, [ ] takes positions. For a data frame, [rows, columns]; leave one side blank to keep everything.

cases[2]                       # 2nd value
#> [1] 12
cases[c(1, 3)]                 # 1st and 3rd values
#> [1] 34 27
linelist[2, ]                  # row 2, all columns
#>   case_id age gender outcome wt_kg ht_cm date_onset      bmi
#> 2    C002  45      m   Death    80   175 2026-01-05 26.12245
linelist[, "age"]              # all rows, column "age"
#> [1] 23 45 31 NA 52  8
linelist[2:4, c("case_id", "age", "outcome")]
#>   case_id age outcome
#> 2    C002  45   Death
#> 3    C003  31 Recover
#> 4    C004  NA    <NA>
linelist[linelist$age > 30 & !is.na(linelist$age), c("case_id", "age")]
#>   case_id age
#> 2    C002  45
#> 3    C003  31
#> 5    C005  52

From the output of summary():

summary(linelist$age)[["Median"]]
#> [1] 31

7.7 Factors

A factor stores categories with a fixed set of levels in a chosen order — important for tables and plots.

severity <- c("high", "low", "medium", "low", "high")
severity <- factor(severity, levels = c("low", "medium", "high"))
levels(severity)
#> [1] "low"    "medium" "high"
table(severity)
#> severity
#>    low medium   high 
#>      2      1      2

7.8 Lists

A list can hold objects of different types and lengths. Many functions return lists.

my_list <- list(
  hospitals = c("Central", "Port", "St. Mark's"),
  n_cases   = 156,
  linelist  = linelist
)
my_list[["hospitals"]]
#> [1] "Central"    "Port"       "St. Mark's"
my_list[["hospitals"]][3]
#> [1] "St. Mark's"

7.9 Removing objects

rm(current_week)              # remove one object
rm(list = ls(all = TRUE))     # remove everything (use with care)

8 Operators and missing values

8.1 Mathematical operators

Operator Meaning Example
+ - * / Add, subtract, multiply, divide 10 / 4
^ Power 2^3
%% Remainder (modulo) 10 %% 3

Common maths functions: sum(), mean(), median(), sd(), min(), max(), round(), sqrt(), log(), abs().

8.2 Comparison and logical operators

Operator Meaning
== Equal to (two = signs)
!= Not equal to
> < >= <= Greater / less than (or equal)
& AND
| OR
! NOT
%in% Value is in a set
age_example <- c(5, 17, 34, 61)
age_example >= 18
#> [1] FALSE FALSE  TRUE  TRUE
age_example >= 18 & age_example < 60
#> [1] FALSE FALSE  TRUE FALSE
linelist$gender == "f"
#> [1]  TRUE FALSE  TRUE FALSE  TRUE FALSE
linelist$outcome %in% c("Death", "Recover")
#> [1]  TRUE  TRUE  TRUE FALSE  TRUE  TRUE

8.3 Missing values: NA

R marks missing values as NA. Most calculations involving NA return NA unless you ask R to remove them.

mean(linelist$age)                 # NA
#> [1] NA
mean(linelist$age, na.rm = TRUE)   # ignore missing values
#> [1] 31.8
is.na(linelist$age)                # TRUE where missing
#> [1] FALSE FALSE FALSE  TRUE FALSE FALSE
sum(is.na(linelist$age))           # count missing values
#> [1] 1

Watch out: x == NA does not test for missing values — always use is.na(x). Also, NA (missing) is different from the text "NA" and from an empty string "".

9 Pipes

A pipe passes the result of one step into the next, so code reads top to bottom like a recipe: “take the linelist, then filter, then count”.

  • %>% — the magrittr/tidyverse pipe .
  • |> — the native pipe built into R 4.1+. For everyday use they behave the same.

Without a pipe (nested — read from the inside out):

round(mean(linelist$age, na.rm = TRUE), 1)
#> [1] 31.8

With a pipe (read top to bottom):

linelist$age |>
  mean(na.rm = TRUE) |>
  round(1)
#> [1] 31.8

With dplyr (introduced fully on Day 3):

library(dplyr)

linelist %>%
  filter(!is.na(outcome)) %>%     # keep rows with a known outcome
  mutate(bmi = wt_kg / (ht_cm / 100)^2) %>%
  count(gender, outcome)

Handbook tip: you can also save intermediate objects (step_1 <- ..., step_2 <- ...). It is longer, but useful when checking each step.

10 Errors, warnings and getting help

Error Warning
What it means R could not run the code R ran the code but something may be wrong
Output Stops; no result Result produced, plus a message
Your action Must fix Read carefully and decide
sqrt("forty-nine")            # error: wrong class of input
#> Error in `sqrt()`:
#> ! non-numeric argument to mathematical function
mean(c("1", "2"))             # warning: argument is not numeric
#> Warning in mean.default(c("1", "2")): argument is not numeric or logical:
#> returning NA
#> [1] NA
undefined_object + 1          # error: object not found
#> Error:
#> ! object 'undefined_object' not found

Most common Day 1 mistakes and fixes

Message or symptom Likely cause Fix
object 'x' not found Typo, wrong case (R is case-sensitive), or object not yet created Check spelling; run the line that creates it
could not find function "x" Package not loaded, or typo Run library(package) or use package::function()
unexpected symbol / unexpected ')' Missing comma, bracket or quote Check that every (, [, " is closed; separate arguments with commas
Console shows + and waits Unclosed bracket or quote Finish the line, or press Esc and retry
non-numeric argument to binary operator Doing maths on text Check class(); convert with as.numeric()

Getting help: read the error message slowly; search it in a web browser; use ?function; check the handbook’s Common errors and Getting help pages; when asking others, share a small reproducible example.

11 Lab exercises (in pairs)

Work in your script day1_basics.R. Comment every step.

Exercise 1 — R as a calculator. A district reported 1,248 cases in a population of 356,000. Calculate the attack rate per 100,000 population, rounded to one decimal place.

Exercise 2 — Objects and classes. Create objects district ("Uyo"), cases (87) and report_date (30 November 2026 as a Date). Print the class of each. Then calculate how many days have passed since 1 January 2026.

Exercise 3 — Vectors. Weekly cases for 8 weeks were: 12, 18, 25, 40, 38, 29, 17, 9.

  1. Store them in a vector weekly_cases.
  2. Calculate the total, mean, and the week with the most cases (hint: which.max()).
  3. Which weeks had more than 20 cases?

Exercise 4 — Data frames. Using the linelist created above:

  1. How many rows and columns does it have?
  2. Show case_id and age for all female cases.
  3. What is the median age, ignoring missing values?
  4. How many cases have a missing outcome?

Exercise 5 — Factors. Convert linelist$gender into a factor with labels in the order "m", "f", then tabulate it.

Exercise 6 — Debugging. Each line below has a mistake. Find and fix it.

Mean(c(1, 2, 3))
sum(c(4, 5, 6)
case_total <- 45 + "10"
linelist$Age

Exercise 7 — Pipes. Rewrite round(sqrt(sum(weekly_cases)), 2) using the pipe.

11.1 Solutions (facilitator copy)

# Exercise 1
round(1248 / 356000 * 100000, 1)                    # 350.6 per 100,000

# Exercise 2
district    <- "Uyo"
cases       <- 87
report_date <- as.Date("2026-11-30")
class(district); class(cases); class(report_date)
report_date - as.Date("2026-01-01")                 # 333 days

# Exercise 3
weekly_cases <- c(12, 18, 25, 40, 38, 29, 17, 9)
sum(weekly_cases); mean(weekly_cases)
which.max(weekly_cases)                             # week 4
which(weekly_cases > 20)                            # weeks 3, 4, 5, 6

# Exercise 4
dim(linelist)
linelist[linelist$gender == "f", c("case_id", "age")]
median(linelist$age, na.rm = TRUE)
sum(is.na(linelist$outcome))

# Exercise 5
linelist$gender <- factor(linelist$gender, levels = c("m", "f"))
table(linelist$gender)

# Exercise 6
mean(c(1, 2, 3))           # R is case-sensitive: mean, not Mean
sum(c(4, 5, 6))            # missing closing bracket
case_total <- 45 + 10      # "10" is text; use a number
linelist$age               # column name is lower case

# Exercise 7
weekly_cases |> sum() |> sqrt() |> round(2)

11.2 Stretch task (if time allows)

Download the handbook practice data and explore the cleaned linelist:

ll <- rio::import("linelist_cleaned.rds")  # adjust the path to where you saved it
dim(ll)
names(ll)
summary(ll$age)
table(ll$gender, ll$outcome, useNA = "ifany")

12 Checkpoint, quiz and wrap-up

Checkpoint: each participant runs day1_basics.R from a fresh session (Session → Restart R, then Run All) without errors.

Quick quiz (10 minutes)

  1. What are the three rules of tidy data?
  2. What is the difference between install.packages() and library()?
  3. What does <- do?
  4. What does class(c(1, 2, "3")) return, and why?
  5. How do you select the age column of linelist?
  6. Why does mean(c(2, NA, 4)) return NA, and how do you fix it?
  7. What is the difference between = and ==?
  8. What does %in% do?
  9. Rewrite round(mean(x), 1) using a pipe.
  10. What is the difference between an error and a warning?

Answer key: (1) each variable a column, each observation a row, each value a cell; (2) install downloads once, library loads each session; (3) assigns a value to an object; (4) "character" — a vector holds one class, so numbers are converted to text; (5) linelist$age; (6) missing values propagate — use na.rm = TRUE; (7) = sets argument values, == tests equality; (8) tests whether each value is in a set; (9) x |> mean() |> round(1); (10) an error stops the code, a warning runs it but flags a possible problem.