Skip to content
AgileLogics

R Cheat Sheet

Learn R from the basics →

Basics

x <- 42
Assign a value
class(x) / typeof(x)
Inspect a value's type
NA / NULL / TRUE / FALSE
Missing value, nothing, logicals
?mean / help(mean)
Open the help page
install.packages("dplyr"); library(dplyr)
Install and load a package

Vectors

v <- c(3, 1, 2)
Create a vector
1:10 / seq(0, 1, by = 0.25)
Sequences
v[1] / v[-1] / v[v > 1]
First element / all but first / filter (1-based)
length(v) / sum(v) / mean(v)
Length and summaries
v * 2
Vectorized arithmetic
sort(v) / rev(v) / unique(v)
Reorder and deduplicate

Strings

paste("a", "b") / paste0("a", "b")
Join with / without a space
sprintf("%.2f", 3.14159)
Format numbers
nchar(s) / toupper(s) / substr(s, 1, 3)
Length, case, substring
grepl("ab", s) / gsub("a", "o", s)
Match / replace with regex

Control Flow & Functions

if (x > 0) { } else { }
Conditional (single value)
ifelse(v > 0, "pos", "neg")
Vectorized conditional
for (i in 1:5) { }
For loop
area <- function(w, h = 1) w * h
Function with a default argument
\(x) x^2
Anonymous function (R 4.1+)
x |> sqrt() |> round(2)
Native pipe (R 4.1+)

Lists & Data Frames

l <- list(name = "Ada", age = 36); l$name
Named list
df <- data.frame(x = 1:3, y = c("a", "b", "c"))
Create a data frame
head(df) / str(df) / summary(df)
Inspect a data frame
df$x / df[df$x > 1, ]
A column / filter rows
read.csv("file.csv")
Read a CSV file

dplyr

filter(df, age > 30)
Keep rows
select(df, name, age)
Keep columns
mutate(df, age2 = age * 2)
Add or change columns
arrange(df, desc(age))
Sort rows
df |> group_by(city) |> summarise(n = n(), avg = mean(age))
Grouped summaries

ggplot2

ggplot(df, aes(x = height, y = weight)) + geom_point()
Scatter plot
geom_line() / geom_col() / geom_histogram()
Line, bar, histogram
aes(colour = group)
Map a variable to colour
labs(title = "...", x = "...", y = "...")
Titles and axis labels
ggsave("plot.png", width = 6, height = 4)
Save the last plot

Statistics

mean(x, na.rm = TRUE) / median(x) / sd(x)
Centre and spread
table(x) / quantile(x)
Counts / quantiles
cor(x, y)
Correlation
model <- lm(y ~ x, data = df); summary(model)
Linear regression
t.test(x, y)
Two-sample t-test