R Cheat Sheet
Last updated
Hello World & assignment
R's idiomatic assignment operator is <- (the = operator also works).
| Operation | Syntax |
|---|---|
| Print a value | print("Hello, World!") |
| Auto-print (console) | "Hello, World!" |
| Concatenate and print | cat("Hi", name, "\n") |
| Assign (idiomatic) | x <- 5 |
| Assign (also valid) | x = 5 |
| Right assign | 5 -> x |
| Comment | # this is a comment |
| Run a script | Rscript app.R |
Data types & vectors
The vector is R's fundamental data structure; even a single value is a length-1 vector.
| Operation | Syntax |
|---|---|
| Numeric vector | v <- c(1, 2, 3) |
| Character vector | s <- c("a", "b") |
| Logical vector | b <- c(TRUE, FALSE) |
| Integer sequence | 1:10 |
| Sequence with step | seq(0, 1, by = 0.1) |
| Repeat values | rep(0, times = 5) |
| Basic types | numeric, character, logical, integer, complex |
| Check / coerce type | class(x), as.numeric("42") |
Vector operations
Operations are vectorized and apply element-wise; indexing is 1-based.
| Operation | Syntax |
|---|---|
| Access element (1-based) | v[1] |
| Slice a range | v[2:4] |
| Logical filtering | v[v > 2] |
| Drop an element | v[-1] |
| Element-wise math | v * 2, v1 + v2 |
| Length | length(v) |
| Common reducers | sum(v), mean(v), max(v) |
| Sort / reverse | sort(v), rev(v) |
| Named vector | c(a = 1, b = 2) |
Data frames
A data frame is a table of columns, each a vector of equal length.
| Operation | Syntax |
|---|---|
| Create a data frame | df <- data.frame(name = c("Ada"), age = c(30)) |
| First / last rows | head(df), tail(df) |
| Dimensions | nrow(df), ncol(df), dim(df) |
| Column names | names(df), colnames(df) |
| Select a column | df$age or df[["age"]] |
| Select rows / columns | df[1, ], df[, "age"] |
| Filter rows | df[df$age > 18, ] |
| Add a column | df$adult <- df$age >= 18 |
| Summary statistics | summary(df) |
| Structure overview | str(df) |
Factors & lists
Factors store categorical data; lists hold elements of mixed types.
| Operation | Syntax |
|---|---|
| Create a factor | f <- factor(c("low", "high")) |
| Factor levels | levels(f) |
| Ordered factor | factor(x, ordered = TRUE) |
| Count by level | table(f) |
| Create a list | l <- list(name = "Ada", scores = c(1, 2)) |
| Access by name | l$name or l[["name"]] |
| Access by position | l[[1]] |
| Sublist (keeps list) | l[1] |
| Length / names | length(l), names(l) |
Control flow
Conditions go in parentheses and blocks in braces.
| Operation | Syntax |
|---|---|
| If / else if / else | if (x > 0) { ... } else if (x < 0) { ... } else { ... } |
| Vectorized if-else | ifelse(v > 0, "pos", "neg") |
| For loop | for (i in 1:10) { ... } |
| For over a vector | for (x in v) { ... } |
| While loop | while (x < 100) { ... } |
| Repeat with break | repeat { if (done) break } |
| Switch | switch(key, a = 1, b = 2) |
| Logical operators | &&, ||, ! (scalar); &, | (vector) |
Functions
Functions are first-class; the last evaluated expression is returned.
| Operation | Syntax |
|---|---|
| Define a function | add <- function(a, b) { a + b } |
| Explicit return | return(a + b) |
| Default argument | greet <- function(name = "World") { ... } |
| Variadic argument | f <- function(...) { sum(...) } |
| Call by name | box(w = 2, h = 3) |
| Anonymous function | function(x) x * 2 |
| Anonymous (shorthand) | \(x) x * 2 |
| Pass to a higher-order fn | sapply(1:3, function(x) x^2) |
The apply family
Apply a function over data without writing explicit loops.
| Function | What it does |
|---|---|
apply(m, 1, sum) | Apply over matrix rows (1) or columns (2) |
sapply(v, f) | Apply over a vector, simplify to a vector/matrix |
lapply(v, f) | Apply over a vector, always return a list |
vapply(v, f, numeric(1)) | Like sapply but with a checked return type |
mapply(f, a, b) | Apply over multiple vectors in parallel |
tapply(x, group, mean) | Apply a function per group |
Map(f, a, b) | Multivariate apply returning a list |
Reduce(+, v) | Fold a vector with a binary function |
Common data-wrangling & stats functions
Frequently used base functions for summarizing and reshaping data.
| Function | What it does |
|---|---|
mean(v) / median(v) | Average / middle value |
sd(v) / var(v) | Standard deviation / variance |
min(v) / max(v) / range(v) | Smallest / largest / both |
quantile(v) | Quantiles (e.g. quartiles) |
table(x) | Frequency counts of values |
unique(v) / duplicated(v) | Distinct values / duplicate flags |
is.na(v) / na.omit(df) | Find / drop missing values |
aggregate(y ~ g, df, mean) | Summarize y by group g |
order(v) | Index order for sorting |
cor(x, y) | Correlation between two vectors |
The R syntax you reach for most, on one page. This R cheat sheet is a quick reference for the core language - assignment and data types, vectors and vector operations, data frames, factors and lists, control flow, functions, and the apply family used across rstats data analysis.
Everything here is base R and runs on a stock install - no extra packages needed. Copy what you need, or try every snippet live in the R playground - no setup required.
R cheat sheet FAQ
Is this R cheat sheet free?
Are R vectors really 1-indexed?
v[1] returns the first element and v[length(v)] returns the last. Negative indices have a special meaning - v[-1] removes the first element rather than counting from the end. This 1-based convention runs through vectors, lists, and data frames alike.What is a data frame in R?
df[rows, columns], select a column with df$name, and inspect it with str(df) or summary(df).