R cheat sheet
A scannable R reference: 14 short snippets across 8 topics, each linking back to the lesson it came from.
At a glance
| Topic | What it covers | |
|---|---|---|
| Installing R and RStudio: the environment | R itself is a command-line interpreter. RStudio is an IDE built on top of it, and every window you click ultimately | lesson |
| Reading and writing data | Column types matter. If you let the reader guess, a column of postal codes becomes numeric and loses its leading zeros | lesson |
| Tidyverse workflow: dplyr and tidyr | .by is the modern replacement for group_by plus ungroup: the grouping exists only for that one verb, so you cannot | lesson |
| Strings and dates with stringr and lubridate | stringr functions take the string first and the pattern second, keep NA as NA rather than dropping it, and are | lesson |
| Statistical modelling: lm, glm and the formula interface | Fit linear and logistic models with the formula syntax, read the summary critically, predict on new data, and check | lesson |
| R Markdown and reproducible reports | Each fenced chunk marked ```{r} in the source runs as R code; a chunk with include = FALSE runs but shows | lesson |
| Package management with CRAN, renv and Bioconductor | renv is not version control for your own code; it pins what your code depends on. Commit the lockfile and the | lesson |
| Debugging R: warnings, factors, NA and performance traps | Tell the four kinds of missing value apart, avoid factor and comparison traps, use the debugger, and stop writing loops | lesson |
Quick snippets
Installing R and RStudio: the environment
Install and orient yourself
# macOS with Homebrew
brew install --cask r rstudio
# Debian and Ubuntu
sudo apt install r-base r-base-dev
# then, in R
R.version.string
.libPaths() # where packages are found, in order
Projects and the working directory
getwd() # the working directory: the source of half of all confusion
setwd("C:/Users/me/analysis") # avoid this in scripts
# a project instead: File > New Project, then paths are relative to the project root
library(here)
here::here() # always the project root, no matter where you run from
read.csv(here("data", "raw", "sales.csv"))
Packages and session facts
install.packages("tidyverse") # once per library
library(tidyverse) # once per session
sessionInfo() # R version, platform, every loaded package
packageVersion("dplyr")
search() # attached packages and objects
ls("package:stats") # what a package exports
?lm # help for a function
??regression # full-text search across help pagesFull lesson: Installing R and RStudio: the environment →
Reading and writing data
Databases
library(DBI)
con <- dbConnect(RPostgres::Postgres(),
dbname = "app", host = "localhost",
user = Sys.getenv("DB_USER"), password = Sys.getenv("DB_PASSWORD"))
df <- dbGetQuery(con, "SELECT id, region, amount FROM orders WHERE amount > $1",
params = list(100))
# use parameters, never paste strings into SQL
dbDisconnect(con)Full lesson: Reading and writing data →
Tidyverse workflow: dplyr and tidyr
Joins
# check the cardinality before you join
customers |> count(customer_id) |> filter(n > 1)
orders |> count(customer_id) |> filter(n > 1)
joined <- orders |>
left_join(customers, by = "customer_id", relationship = "many-to-one") |>
anti_join(blacklist, by = "customer_id")
# which rows failed to match?
unmatched <- orders |> anti_join(customers, by = "customer_id")Full lesson: Tidyverse workflow: dplyr and tidyr →
Strings and dates with stringr and lubridate
Time zones and arithmetic
x <- ymd_hms("2026-03-29 00:30:00", tz = "Europe/London")
x + hours(2) # crosses the DST jump: the wall clock skips an hour
x + dhours(2) # exactly 7200 seconds later
force_tz(x, "UTC") # reinterpret in another zone
with_tz(x, "America/New_York") # convert to another zoneFull lesson: Strings and dates with stringr and lubridate →
Statistical modelling: lm, glm and the formula interface
The formula interface
# y depends on x, with an intercept by default
lm(mpg ~ wt, data = mtcars)
# more terms
lm(mpg ~ wt + hp + factor(cyl), data = mtcars)
lm(mpg ~ wt * hp, data = mtcars) # main effects AND interaction
lm(mpg ~ wt + I(wt^2), data = mtcars) # protect arithmetic with I()
lm(mpg ~ ., data = mtcars) # everything else in the frame
lm(mpg ~ wt - 1, data = mtcars) # no intercept
Diagnostics
par(mfrow = c(2, 2))
plot(fit) # residuals, scale-location, leverage, influence
par(mfrow = c(1, 1))
car::vif(fit) # variance inflation: above about 5 is worth a look
shapiro.test(residuals(fit)) # normality of residuals, for small samples
cor(model.matrix(fit)[, -1]) # collinearity between predictorsFull lesson: Statistical modelling: lm, glm and the formula interface →
R Markdown and reproducible reports
Structure of a document
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
fig.width = 7, fig.height = 4, dpi = 150)
library(readr)
df <- read_csv("data/sales.csv")
library(ggplot2)
ggplot(df, aes(month, revenue)) + geom_col()
Rendering and parameters
Rscript -e 'rmarkdown::render("report.Rmd", output_file = "build/aug.html")'
# parameterised rendering, one report per month
Rscript -e 'rmarkdown::render("report.Rmd", params = list(month = "2026-08"), output_dir = "build")'
Rendering and parameters
# a parameterised render driven from R
library(rmarkdown)
for (m in c("2026-06", "2026-07", "2026-08")) {
render("report.Rmd",
params = list(month = m),
output_file = paste0("report-", m, ".html"),
envir = new.env()) # a clean environment per run
}Full lesson: R Markdown and reproducible reports →
Package management with CRAN, renv and Bioconductor
Project libraries with renv
renv::init() # project-local library plus renv.lock
renv::install("[email protected]") # installs into the project, not the user library
renv::snapshot() # write current versions into the lockfile
renv::restore() # rebuild the library from the lockfile
renv::status()
renv::upgrade() # check for newer versions without installing
renv::status() # confirm the library matches the lockfile
renv::diagnostics() # when the two disagree and you need detail
Licences and provenance
# licences of everything installed
pkgs <- installed.packages()[, c("Package", "Version", "License")]
head(pkgs[order(pkgs$Package), ])
# the licence of one package, plus its dependencies
pak::pkg_deps("dplyr")[, c("package", "version", "needscompilation")]Full lesson: Package management with CRAN, renv and Bioconductor →
Debugging R: warnings, factors, NA and performance traps
NA, NaN, NULL and empty strings
x <- c(1, NA, 3, NaN)
mean(x) # NA: any missing value poisons the result
mean(x, na.rm = TRUE) # 2, once NaN and NA are excluded
x == NA # all NA: comparison with a missing value is unknown
is.na(x) # the only correct test
# filtering with a condition containing NA silently drops rows
df[df$amount > 100, ] # NA rows vanish; is that what you intended?
subset(df, amount > 100)Full lesson: Debugging R: warnings, factors, NA and performance traps →
FAQ
Is this R cheat sheet free to use?
Where do the examples come from?
How do I go deeper than a cheat sheet?
Related cheat sheets
Python 3 NumPy pandas Matplotlib Jupyter Notebook Flask
Last refreshed 2026-09-27.