Skip to main content
Quick Reference

R Cheatsheet

Base R on one page — vectors, missing values, data frames, apply, and the traps around 1:length, sample, and drop.

10 sections 10 tables 14 code snippets

Run a script

A file

Rscript analysis.R

A vector

pages <- c(412, 300, 180)

The names

NameMeaning
RscriptRuns a file. The interactive prompt is > and q() leaves it
<-Assigns a name. Inside a call, = names an argument instead
#A comment to the end of the line
c()Combines values and flattens nested calls of c
A numberA vector of length 1. 1 is double. 1L is integer
One typec(1, "a") becomes text. A vector cannot mix types

This page is base R. dplyr, ggplot2, and the rest of the tidyverse are left out.

Vectors

The first value

pages[1]

Every position

seq_along(pages)

Index rules

ExpressionResult
pages[1]The first value. Positions start at 1
pages[0]A length-0 vector. It is not an error and not the first value
pages[-1]Every value except the first. Do not mix negative and positive indexes
1:31, 2, and 3. Both ends are included
1:n - 1(1:n) - 1. The colon binds tighter than minus
RecyclingA shorter vector repeats when the lengths divide. Otherwise R warns

Missing values

Find the gaps

is.na(pages)

Three kinds of empty

ValueMeaning
NAA missing value. It has length 1. pages == NA is NA, not FALSE
NULLThe object is absent. Length 0. c() drops NULL
NaNNot a number, such as 0/0. Test with is.nan
InfInfinity from dividing by zero
is.naTrue for NA and for NaN
na.rm = TRUETells sum and mean to skip NA

Subsetting

Pick and drop

pages[c(1, 3)]
pages[-1]

How a subset is chosen

FormDetail
Integer indexpages[c(1, 3)] keeps those positions, in that order
Negative indexpages[-1] drops position 1
Logical indexKeeps the TRUE positions. An NA in the index inserts NA
NameAfter names(pages) <- c("a", "b", "c"), pages["a"] selects by name
Past the endpages[10] is NA. It does not stop the script
whichThe integer positions that are TRUE. An NA condition is skipped

Conditions

One value for if

if (length(pages) > 0) {
  sum(pages, na.rm = TRUE)
}

Which operator

OperatorUse
ifNeeds one logical value. A longer condition warns and only the first value is used
& and |Compare every element and return a logical vector
&& and ||Compare one value and stop early. This is the pair for if
ifelseA vector result. The output type can change
any and allCollapse a logical vector to one value
TRUE and FALSEReserved. T and F are ordinary names and can be overwritten

Functions

A total

total <- function(x) {
  sum(x, na.rm = TRUE)
}

Call rules

FactDetail
Return valueThe last expression. return leaves early
Defaultsfunction(x, digits = 0) uses 0 when the caller omits digits
NamesArguments can be passed by name, in any order, after the positional ones
...Forwards extra arguments to another function
ScopeThe function sees the environment where it was created
Short formSince R 4.1 a one-argument function can be written with \(x)

Lists

One element, unwrapped

book <- list(title = "Dune", pages = 412)
book[["title"]]

List rules

FormResult
listHolds mixed types. Each element keeps its own type
book[1]A list of length 1
book[[1]]The element itself, with the list wrapper removed
book$titleSame idea as [[, but a partial name can match
book[["title"]]An exact name. This is the form to prefer
Missing [[An index past the end stops with an error. [ past the end is a NULL element

Data frames

Rows that match

books <- data.frame(
  title = c("Dune", "Emma"),
  pages = c(412, 180)
)
books[books$pages > 200, ]

Column rules

FactDetail
ColumnsEqual-length vectors. A shorter column recycles only when the length divides
StringsSince R 4.0, data.frame keeps strings as character
books$pagesOne column as a vector
books[rows, cols]The comma is required. An empty side means every row or every column
dropThe default is TRUE. books[, 1] becomes a vector
FactorsA value outside the levels becomes NA and R warns

Apply and the pipe

A fixed result type

vapply(pages, as.character, character(1))

The base pipe

pages |> sum(na.rm = TRUE)

Which tool

ToolResult
lapplyAlways a list, one element per input
sapplySimplifies the list. The shape can change with the data
vapplyYou pass a template such as character(1) or numeric(1)
applyA margin of a matrix. matrix fills down each column first
|>Since R 4.1. The left value becomes the first argument. The right side must be a call
stats::medianCalls one function without attaching the package

Interview traps

Traps worth memorising

TrapWhat happensPrefer
1:length(x) when x is empty1:0 is 1 then 0, so the body runs twiceseq_along(x)
sample(5)A length-1 number of at least 1 means sample from 1:5x[sample.int(length(x))]
books[, 1]drop defaults to TRUE, so one column comes back as a vectorbooks[, 1, drop = FALSE]
pages == NAEvery comparison is NA, so a filter keeps nothing usefulis.na(pages)
if (pages > 100)Only the first value is used, with a warningpages[pages > 100], or any and all
1:n - 1The colon runs first, then 1 is subtracted1:(n - 1)
T <- FALSET and F are ordinary namesTRUE and FALSE
book$ti$ can match a longer namebook[["title"]]
<<-Writes in a parent environmentReturn the value
c(1, "a")The number becomes textA list for mixed types
sapplyThe result shape depends on the valuesvapply with a template
pages[10][ past the end is NACheck length before you index

Positions of any length

seq_along(pages)

A shuffle that keeps length 1

pages[sample.int(length(pages))]

How to use this page: build a vector with c, test gaps with is.na, and walk positions with seq_along. Keep one-column subsets with drop = FALSE.