Skip to content

R - Cheatsheet

This cheatsheet provides a concise overview of modern R programming, focusing on the tidyverse ecosystem for efficient and readable data analysis. It covers key concepts from basic syntax to data visualization and modeling.

Core commands for interacting with your R session.

# Get help on a function
?mean
help(mean)
# Install a package from CRAN
install.packages("dplyr")
# Load a package into the session
library(dplyr)
# List objects in the current workspace
ls()
# Remove an object
rm(my_variable)

The building blocks of R code.

# This is a comment
# Variable assignment (<- is the preferred convention)
my_variable <- "Hello R!"
my_number <- 100
# The Pipe Operator (from magrittr, loaded with tidyverse)
# Passes the result of one function to the next
# x %>% f(y) is equivalent to f(x, y)
# Since R 4.1, a native pipe |> is also available
# --- Arithmetic Operators ---
# +, -, *, /, ^ (exponent), %% (modulus), %/% (integer division)
result <- (5 + 3) * 2 # 16
# --- Relational & Logical Operators ---
# >, <, >=, <=, == (equal to), != (not equal to)
# & (element-wise AND), | (element-wise OR), ! (NOT)
# && (short-circuit AND), || (short-circuit OR)
TRUE & FALSE # FALSE
x > 5 & x < 10

R’s primary objects for storing data.

Data StructureDescriptionExample
VectorA 1D sequence of elements of the same type.c(1, 2, 3) (numeric), c("a", "b", "c") (character)
ListA 1D collection of elements of any type.list(name = "John", age = 30, scores = c(88, 95))
MatrixA 2D array of elements of the same type.matrix(1:6, nrow = 2, ncol = 3)
Data FrameA 2D, table-like structure where columns can have different types.data.frame(id = 1:3, name = c("A", "B", "C"))
TibbleA modern, enhanced data frame (from tidyverse). Better printing and subsetting.tibble(id = 1:3, name = c("A", "B", "C"))
FactorA vector for categorical data with defined levels.factor(c("low", "high", "low"), levels = c("low", "medium", "high"))

Use the readr and readxl packages for fast and reliable data import.

library(readr)
library(readxl)
library(writexl)
# Read a CSV file (returns a tibble)
my_data_csv <- read_csv("path/to/my_file.csv")
# Read an Excel file (specify sheet by name or number)
my_data_excel <- read_excel("path/to/my_file.xlsx", sheet = "Sheet1")
# Write data to a CSV file
write_csv(my_data_csv, "output/data.csv")
# Write data to an Excel file
write_xlsx(my_data_excel, "output/data.xlsx")

The core verbs of dplyr for data manipulation, often used with the pipe %>%.

library(dplyr)
# Example dataset
data <- starwars
# Filter rows
droids <- data %>% filter(species == "Droid")
# Select columns
name_and_height <- data %>% select(name, height, mass)
# Create or modify columns
heavy_hitters <- data %>% mutate(bmi = mass / ((height/100)^2))
# Arrange (sort) rows
sorted_by_height <- data %>% arrange(desc(height))
# Summarize data, often with group_by
species_summary <- data %>%
filter(!is.na(mass)) %>%
group_by(species) %>%
summarize(
count = n(),
avg_mass = mean(mass)
) %>%
arrange(desc(count))

ggplot2 uses a layered grammar of graphics. You build plots by adding layers.

library(ggplot2)
# The structure of a ggplot:
# ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) + <GEOM_FUNCTION>()
# Scatter plot
ggplot(data = starwars, aes(x = mass, y = height)) +
geom_point(aes(color = gender)) + # Add color mapping
labs(
title = "Height vs. Mass of Star Wars Characters",
x = "Mass (kg)",
y = "Height (cm)",
caption = "Data from the dplyr package"
) +
theme_minimal()
# Bar plot of species counts
starwars %>%
count(species, sort = TRUE) %>%
filter(n > 1) %>%
ggplot(aes(x = reorder(species, n), y = n)) +
geom_col() +
coord_flip() + # Flip coordinates for readability
labs(title = "Most Common Species", x = "Species", y = "Count")
# If-else statement
if (x > 10) {
print("x is large")
} else {
print("x is small")
}
# For loop
for (i in 1:5) {
print(i)
}
# Writing a custom function
calculate_bmi <- function(mass_kg, height_m) {
if (!is.numeric(mass_kg) || !is.numeric(height_m)) {
stop("Inputs must be numeric.")
}
bmi <- mass_kg / (height_m ^ 2)
return(bmi)
}
# Using the function
calculate_bmi(70, 1.75)

Fitting and inspecting a simple linear model.

# Fit a linear model: predict mpg from weight
model <- lm(mpg ~ wt, data = mtcars)
# View model summary
summary(model)
# Use 'broom' to get tidy model output
library(broom)
tidy(model) # Coefficients as a tibble
glance(model) # Model summary statistics as a tibble
ToolPurpose
R Markdown (.Rmd)A file format for making dynamic documents with R. Combine code, its output (plots, tables), and narrative text into high-quality reports (HTML, PDF, Word).
renv packageA dependency management tool. It creates a project-specific library of packages, ensuring your code runs the same way for you and others, now and in the future.