R Cheat-sheet
The handful of R you need for the whole book, in one place.
Setup (every script)
install.packages("pacman") # once only
pacman::p_load(rio, here, tidyverse, janitor) # load the spine
dat <- import(here("data", "file.csv")) # read dataLook at data
glimpse(dat) # columns, types, first values
dim(dat); names(dat); head(dat)
summary(dat) # ranges and averages
tabyl(dat, column) # frequency table (janitor)Wrangle (tidyverse)
dat |> filter(species == "Atlantic salmon") # keep rows
dat |> select(week, deaths) # keep columns
dat |> mutate(prev = n_positive / n_sampled * 100) # new column
dat |> group_by(species) |> summarise(m = mean(x)) # summarise by group
dat |> arrange(desc(x)) # sortSummaries
mean(x); median(x); sd(x); IQR(x); quantile(x)
range(x); var(x)
exp(mean(log(x))) # geometric mean (loads, titres)Plot (ggplot2)
ggplot(dat, aes(x = week, y = deaths)) + geom_line()
ggplot(dat, aes(x = n_stocked)) + geom_histogram(bins = 10)
ggplot(dat, aes(x = species, y = temp)) + geom_boxplot()Epidemiology one-liners
binom.confint(x, n, methods = "wilson") # CI for a proportion
epi.2by2(tab, method = "cohort.count") # RR, OR, attributable fractions
epi.tests(tab) # Se, Sp, PPV, NPV
mantelhaen.test(table(exp, out, confounder)) # confounding-adjusted OR
coxph(Surv(time, event) ~ group, data = d) # survival / hazard ratio
glm(y ~ x, family = binomial) # logistic regression
metagen(TE, seTE, sm = "RR") # meta-analysisGetting help
?mean # help page
vignette() # package tutorials