Menu

R Cheat Sheet

Last updated

Hello World & assignment

R's idiomatic assignment operator is <- (the = operator also works).

OperationSyntax
Print a valueprint("Hello, World!")
Auto-print (console)"Hello, World!"
Concatenate and printcat("Hi", name, "\n")
Assign (idiomatic)x <- 5
Assign (also valid)x = 5
Right assign5 -> x
Comment# this is a comment
Run a scriptRscript app.R

Data types & vectors

The vector is R's fundamental data structure; even a single value is a length-1 vector.

OperationSyntax
Numeric vectorv <- c(1, 2, 3)
Character vectors <- c("a", "b")
Logical vectorb <- c(TRUE, FALSE)
Integer sequence1:10
Sequence with stepseq(0, 1, by = 0.1)
Repeat valuesrep(0, times = 5)
Basic typesnumeric, character, logical, integer, complex
Check / coerce typeclass(x), as.numeric("42")

Vector operations

Operations are vectorized and apply element-wise; indexing is 1-based.

OperationSyntax
Access element (1-based)v[1]
Slice a rangev[2:4]
Logical filteringv[v > 2]
Drop an elementv[-1]
Element-wise mathv * 2, v1 + v2
Lengthlength(v)
Common reducerssum(v), mean(v), max(v)
Sort / reversesort(v), rev(v)
Named vectorc(a = 1, b = 2)

Data frames

A data frame is a table of columns, each a vector of equal length.

OperationSyntax
Create a data framedf <- data.frame(name = c("Ada"), age = c(30))
First / last rowshead(df), tail(df)
Dimensionsnrow(df), ncol(df), dim(df)
Column namesnames(df), colnames(df)
Select a columndf$age or df[["age"]]
Select rows / columnsdf[1, ], df[, "age"]
Filter rowsdf[df$age > 18, ]
Add a columndf$adult <- df$age >= 18
Summary statisticssummary(df)
Structure overviewstr(df)

Factors & lists

Factors store categorical data; lists hold elements of mixed types.

OperationSyntax
Create a factorf <- factor(c("low", "high"))
Factor levelslevels(f)
Ordered factorfactor(x, ordered = TRUE)
Count by leveltable(f)
Create a listl <- list(name = "Ada", scores = c(1, 2))
Access by namel$name or l[["name"]]
Access by positionl[[1]]
Sublist (keeps list)l[1]
Length / nameslength(l), names(l)

Control flow

Conditions go in parentheses and blocks in braces.

OperationSyntax
If / else if / elseif (x > 0) { ... } else if (x < 0) { ... } else { ... }
Vectorized if-elseifelse(v > 0, "pos", "neg")
For loopfor (i in 1:10) { ... }
For over a vectorfor (x in v) { ... }
While loopwhile (x < 100) { ... }
Repeat with breakrepeat { if (done) break }
Switchswitch(key, a = 1, b = 2)
Logical operators&&, ||, ! (scalar); &, | (vector)

Functions

Functions are first-class; the last evaluated expression is returned.

OperationSyntax
Define a functionadd <- function(a, b) { a + b }
Explicit returnreturn(a + b)
Default argumentgreet <- function(name = "World") { ... }
Variadic argumentf <- function(...) { sum(...) }
Call by namebox(w = 2, h = 3)
Anonymous functionfunction(x) x * 2
Anonymous (shorthand)\(x) x * 2
Pass to a higher-order fnsapply(1:3, function(x) x^2)

The apply family

Apply a function over data without writing explicit loops.

FunctionWhat 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.

FunctionWhat 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?
Yes. This R cheat sheet is completely free, with no sign-up required. Bookmark it and come back whenever you need to look up a vector operation, data-frame method, or stats function.
Are R vectors really 1-indexed?
Yes. Unlike most programming languages, R indexing starts at 1, so 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?
A data frame is R's table type: a collection of columns where every column is a vector of the same length, and different columns can hold different types (numbers, text, factors). It is the standard structure for datasets - rows are observations and columns are variables - and you index it as df[rows, columns], select a column with df$name, and inspect it with str(df) or summary(df).
Can I practice R online?
Yes. Open the R playground to run any snippet from this cheat sheet in your browser - no R or RStudio to install. When you want structure, Coddy's free interactive R course takes you from vectors and data frames to the apply family and statistics step by step.
Is this cheat sheet good for beginners?
Yes. It is organized from the most common topics (assignment, vectors, data frames) down to advanced ones (the apply family and stats functions), so you can use the top sections on day one and grow into the rest.
Coddy programming languages illustration

Learn R with Coddy

GET STARTED