| Item | Detail |
|---|---|
| Level | Beginner — no prior R or coding experience assumed |
By the end of Day 1, each participant can:
package::function().<-, and check and convert their
class.$ and [ ].%in%, and
handle missing values (NA).%>% or
|>).R is a free, open-source programming language for statistics and graphics. For public-health work it offers:
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 |
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:
R and Excel can work together: R imports and exports Excel files easily (with packages such as rio and openxlsx).
R works best with data structured for machines, not for human eyes. Tidy data follows three rules:
| 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.
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.
#> [1] 4
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:
snake_case
(e.g. case_count, date_onset) — no
spaces.x <- 5, not x<-5).# Load packages ---- (RStudio turns these into a clickable
outline).A function takes inputs (arguments) and returns an output. Arguments go inside round brackets, separated by commas.
#> [1] 7
#> [1] 3.14
#> [1] 3.14
Naming arguments makes code easier to read and avoids mistakes when the order is unclear.
#> [1] NA
#> [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).
A package is a collection of functions. Base R comes with many functions; packages add thousands more.
pacman::p_load() installs a package if it is missing,
then loads it — one line does both.
package::function()The double colon calls a function from a package without loading the whole package, and makes clear where a function comes from.
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.
You create an object with the assignment operator
<- (“gets”). I totally discourage using
= for assignment.
#> [1] "2018-W10"
#> [1] 312
Objects appear in the Environment pane. Assigning a new value to the same name overwrites it without warning.
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 |
#> [1] "numeric"
#> [1] "character"
#> [1] "logical"
#> [1] "Date"
Converting classes — as.numeric(),
as.character(), as.integer(),
as.Date(), factor(). Testing
classes — is.numeric(),
is.character(), is.factor().
#> [1] "numeric"
#> [1] "1" "2" "three" "4" "5"
#> [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.
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
#> [1] 123
#> [1] 24.6
#> [1] 41
Useful shortcuts: 1:10 makes a sequence;
seq(0, 100, by = 10) makes stepped sequences;
rep("A", 3) repeats values.
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:
#> [1] 6
#> [1] 7
#> [1] "case_id" "age" "gender" "outcome" "wt_kg"
#> [6] "ht_cm" "date_onset"
#> '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" ...
#> 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).
$$ selects one column from a data frame.
#> [1] 23 45 31 NA 52 8
#> [1] "character"
#>
#> 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
[ ]For a vector, [ ] takes positions. For a data frame,
[rows, columns]; leave one side blank to keep
everything.
#> [1] 12
#> [1] 34 27
#> case_id age gender outcome wt_kg ht_cm date_onset bmi
#> 2 C002 45 m Death 80 175 2026-01-05 26.12245
#> [1] 23 45 31 NA 52 8
#> case_id age outcome
#> 2 C002 45 Death
#> 3 C003 31 Recover
#> 4 C004 NA <NA>
#> case_id age
#> 2 C002 45
#> 3 C003 31
#> 5 C005 52
From the output of summary():
#> [1] 31
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"
#> severity
#> low medium high
#> 2 1 2
| 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().
| Operator | Meaning |
|---|---|
== |
Equal to (two = signs) |
!= |
Not equal to |
> < >=
<= |
Greater / less than (or equal) |
& |
AND |
| |
OR |
! |
NOT |
%in% |
Value is in a set |
#> [1] FALSE FALSE TRUE TRUE
#> [1] FALSE FALSE TRUE FALSE
#> [1] TRUE FALSE TRUE FALSE TRUE FALSE
#> [1] TRUE TRUE TRUE FALSE TRUE TRUE
NAR marks missing values as NA. Most calculations
involving NA return NA unless you ask R to
remove them.
#> [1] NA
#> [1] 31.8
#> [1] FALSE FALSE FALSE TRUE FALSE FALSE
#> [1] 1
Watch out:
x == NAdoes not test for missing values — always useis.na(x). Also,NA(missing) is different from the text"NA"and from an empty string"".
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):
#> [1] 31.8
With a pipe (read top to bottom):
#> [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.
| 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 |
#> Error in `sqrt()`:
#> ! non-numeric argument to mathematical function
#> Warning in mean.default(c("1", "2")): argument is not numeric or logical:
#> returning NA
#> [1] NA
#> 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.
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.
weekly_cases.which.max()).Exercise 4 — Data frames. Using the
linelist created above:
case_id and age for all female
cases.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.
Exercise 7 — Pipes. Rewrite
round(sqrt(sum(weekly_cases)), 2) using the pipe.
# 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)Checkpoint: each participant runs
day1_basics.R from a fresh session (Session →
Restart R, then Run All) without errors.
Quick quiz (10 minutes)
install.packages() and
library()?<- do?class(c(1, 2, "3")) return, and why?age column of
linelist?mean(c(2, NA, 4)) return NA, and
how do you fix it?= and
==?%in% do?round(mean(x), 1) using a pipe.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.