R - Cheatsheet
Modern R Cheatsheet
Section titled “Modern 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.
1. The R Environment
Section titled “1. The R Environment”Core commands for interacting with your R session.
# Get help on a function?meanhelp(mean)
# Install a package from CRANinstall.packages("dplyr")
# Load a package into the sessionlibrary(dplyr)
# List objects in the current workspacels()
# Remove an objectrm(my_variable)2. Basic Syntax & Operators
Section titled “2. Basic Syntax & Operators”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 # FALSEx > 5 & x < 103. Core Data Structures
Section titled “3. Core Data Structures”R’s primary objects for storing data.
| Data Structure | Description | Example |
|---|---|---|
| Vector | A 1D sequence of elements of the same type. | c(1, 2, 3) (numeric), c("a", "b", "c") (character) |
| List | A 1D collection of elements of any type. | list(name = "John", age = 30, scores = c(88, 95)) |
| Matrix | A 2D array of elements of the same type. | matrix(1:6, nrow = 2, ncol = 3) |
| Data Frame | A 2D, table-like structure where columns can have different types. | data.frame(id = 1:3, name = c("A", "B", "C")) |
| Tibble | A modern, enhanced data frame (from tidyverse). Better printing and subsetting. | tibble(id = 1:3, name = c("A", "B", "C")) |
| Factor | A vector for categorical data with defined levels. | factor(c("low", "high", "low"), levels = c("low", "medium", "high")) |
4. Data Import & Export
Section titled “4. Data Import & Export”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 filewrite_csv(my_data_csv, "output/data.csv")
# Write data to an Excel filewrite_xlsx(my_data_excel, "output/data.xlsx")5. Data Transformation with dplyr
Section titled “5. Data Transformation with dplyr”The core verbs of dplyr for data manipulation, often used with the pipe %>%.
library(dplyr)
# Example datasetdata <- starwars
# Filter rowsdroids <- data %>% filter(species == "Droid")
# Select columnsname_and_height <- data %>% select(name, height, mass)
# Create or modify columnsheavy_hitters <- data %>% mutate(bmi = mass / ((height/100)^2))
# Arrange (sort) rowssorted_by_height <- data %>% arrange(desc(height))
# Summarize data, often with group_byspecies_summary <- data %>% filter(!is.na(mass)) %>% group_by(species) %>% summarize( count = n(), avg_mass = mean(mass) ) %>% arrange(desc(count))6. Data Visualization with ggplot2
Section titled “6. Data Visualization with ggplot2”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 plotggplot(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 countsstarwars %>% 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")7. Control Flow & Functions
Section titled “7. Control Flow & Functions”# If-else statementif (x > 10) { print("x is large")} else { print("x is small")}
# For loopfor (i in 1:5) { print(i)}
# Writing a custom functioncalculate_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 functioncalculate_bmi(70, 1.75)8. Basic Modeling
Section titled “8. Basic Modeling”Fitting and inspecting a simple linear model.
# Fit a linear model: predict mpg from weightmodel <- lm(mpg ~ wt, data = mtcars)
# View model summarysummary(model)
# Use 'broom' to get tidy model outputlibrary(broom)tidy(model) # Coefficients as a tibbleglance(model) # Model summary statistics as a tibble9. Reproducible Analysis
Section titled “9. Reproducible Analysis”| Tool | Purpose |
|---|---|
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 package | A 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. |