Base R cheatsheet

Author

Rens Holmer & Mark Sterken

Published

February 10, 2026

Atomic Data Types

Type Example Check
logical TRUE is.logical(x)
integer 5L is.integer(x)
double 3.14 is.double(x)
character "a" is.character(x)
complex 1+2i is.complex(x)
raw as.raw(1) is.raw(x)

Special Values

Value Meaning
NA Missing
NaN Undefined number
Inf Infinity
NULL No object
length(NULL) 0

Data structures

Structure Dim Homogeneous?1 Example
vector \(1D\) Yes c(1, 2, 3)
list \(1D\) No list(1, "a")
matrix \(2D\) Yes matrix(1:4, 2)
array \(nD\) Yes array(1:8, c(2, 2, 2))
data.frame \(2D\) Yes (columns) / No (rows) data.frame(a = 1, b = "x")
tibble2 \(2D\) No tibble(a = 1, b = "x")
factor \(1D\) Yes factor(c("a", "b"))

Subsetting rules

Object [ ] [[ ]]
vector subset element
list sublist element
data.frame df slice column
tibble tibble vector

Type Coercion

logical –> integer –> double –> character

Examples

c(TRUE, 2)
# becomes: c(1, 2)

c(1, "a")
# becomes: c("1", "a")

Writing functions

(Named) function definition

#' Arbitrary function
#'
#'@description
#'  `function_name` is an example function to highlight function syntax details.
#'  This function calls `other_function` as part of its implementation
#'  The documentation style is part of the roxygen package
#'
#'@param argument1 Description of the first argument (with it's type).
#'@param argument2 Description of the second argument (with it's type).
#'@param argument3 Description of the third argument (with it's type).
#'@param ... Arbitrary additional arguments pass on to `other_function`.
#'
#'@returns Brief description of type (and e.g. shape) of what the function returns
function_name <- function(argument1, argument2, argument3 = 'default_value', ...){
  # Function body
  # `...` are arbitrary arguments that can be passed on to other functions
  some_val <- other_function(argument1, ...)
  return(return_value)
}

Using (AKA calling) a (named) function

# Positional arguments only
value <- function_name(value1, value2)

# Combining positional and named arguments (in arbitrary order)
value <- function_name(argument3 = 'other_value', value1, value2)

# Adding arbitrary arguments that will be passed on 
# (only if function definition allows it)
value <- function_name(
  value1, # goes to argument1
  value2, # goes to argument2
  value3, # goes to argument3
  arbitrary_value4, # goes to ..., so (in this case) gets passed on to `other_function`
)

Anonymous functions

# Some functions take other functions as arguments, these other function can be 
# supplied in-line and are called 'anonymous' functions
value <- some_function(
  input, 
  function(el) {
    # ...do something with el here
    # Note that `some_function` determines how this anonymous function will be called
  }
)

# Example
sapply(1:4, function(i){ i**2 })
# This returns: [1]  1  4  9 16

Control flow

Conditional execution

# Classic if/else statement (val is a single value)
if (val > 1) {
  # Do something
} else {
  # Do something else
}

# Vectorized version (val is a vector)
# new_val will be a vector with values 'large' and 'small'
new_val <- ifelse(val > 1, 'large', 'small')

For loops

for (i in x) {
  # do something with element i from collection x
} 

While loops

while (condition){
  # Do something while condition evaluates to TRUE
  # Stops when `condition` changes, when `break` is used, or (when inside a function)
  # when a `return` statement is used
  if (other_condition){
    break
  }
}

Repeat loops

repeat {
  # Do something repeatedly
  # When not in a function body, the only way to stop this is by using `break`
  # Inside a function body, a `return` statement also terminates the loop
  if (condition) {
    break
  }
}

The apply functions

Error handling

# If no error occurs, `try` returns the normal return value, otherwise an error object
result_or_error <- try(some_function_call(arg1, arg2))

# `tryCatch` provides more fine grained control over what to do with errors or warnings
result <- tryCatch(
  function_call(arg1),
  error = function(e){
    # Optionally do something with the error object `e`
    return('Something to return on error')
  },
  warning = function(w){
    # Optionally do something with the warning object `w`
    return('Something to return on warning')
  }
)

Operators

Category Operator Name / Meaning Notes
ARITHMETIC OPERATORS
+ Addition Element-wise
- Subtraction Element-wise
* Multiplication Element-wise
/ Division Element-wise
^, ** Power Right associative
%% Modulo Remainder
%/% Integer division Floor division
COMPARISON OPERATORS
== Equal Vectorised
!= Not equal Vectorised
< Less than Vectorised
<= Less or equal Vectorised
> Greater than Vectorised
>= Greater or equal Vectorised
LOGICAL OPERATORS
& AND Vectorised
| OR Vectorised
! NOT Vectorised
&& AND Short-circuit
|| OR Short-circuit
ASSIGNMENT OPERATORS
<- Assign Standard
= Assign Contextual
-> Right assign Rare
<<- Super assign Parent env
->> Super right assign Parent env
SUBSETTING / EXTRACTION
[ Subset Preserves type
[[ Extract Single element
$ Named extract Lists / data frames
SPECIAL INFIX OPERATORS
%in% Membership Set inclusion
%*% Matrix multiply Linear algebra
%% Modulo Arithmetic
%/% Integer division Arithmetic
%>% Pipe (magrittr) Tidyverse
%<>% Compound pipe Tidyverse
PIPE (BASE R)
|> Base pipe R ≥ 4.1
FORMULA / MODELING
~ Formula Symbolic relation
NAMESPACE OPERATORS
:: Exported access Package API
::: Internal access Non-exported
INTROSPECTION / OOP / Help
@ S4 slot access Formal classes
? Help Documentation
?? Search help Full-text

Basic functions covered in the course

R Functions by Category

File system

Function / Syntax Description
setwd() Set the working directory.

Package management

Function / Syntax Description
install.packages() Install R packages from CRAN.
library() Load an installed package.

Data import

Function / Syntax Description
read.delim() Read tab‑delimited text files.
read.csv() Read comma‑separated CSV files.
read.csv2() Read semicolon‑separated CSV files.
readxl::read_xlsx() Read Excel .xlsx files.

Data exploration

Function / Syntax Description
head() Show the first 6 rows of data.
tail() Show the last 6 rows of data.
summary() Show descriptive statistics.
table() Create frequency tables.

Dimensions

Function / Syntax Description
ncol() Number of columns.
nrow() Number of rows.
dim() Dimensions (rows × columns).

Statistics

Function / Syntax Description
shapiro.test() Shapiro–Wilk normality test.
t.test() Student’s t‑test.
wilcox.test() Wilcoxon non‑parametric test.
cor() calculates the correlation coefficient
cor.test() calculates the significance of correlation
lm() runs a linear model

Visualization

Function / Syntax Description
heatmap() Generate heatmap from a numeric matrix.
plot() Base R generic plotting function.

  1. i.e. all values are of the same type↩︎

  2. Tidyverse only↩︎