Course R
R Cheatsheet
A quick, printable reference with essential R syntax: <- assignment, vectorized operations, matrices, data frames, loops, functions, and handling NA missing values. Print to PDF with Ctrl/Cmd + P.
Save or print this cheatsheet as PDF
Print-ready layout: open in one click and save as PDF from your browser, no account or email required.
0. Core R Invariants & Pitfalls to Avoid
Five R behaviors that routinely trip up data pipelines and statistical code.
- Indexing in R is 1-based (never 0-based): x[0] returns a typed empty vector instead of raising an error.
- Missing NA values poison aggregations unless na.rm = TRUE is passed; check with is.na(x), never x == NA.
- Vectors of mismatched lengths silently recycle shorter vectors during arithmetic (warning only if non-multiple).
- Selecting one column via mat[, 1] or df[, 1] drops down to a vector by default: add drop = FALSE to keep 2D shape.
- Use <- for variable assignment and reserve = for named function arguments.
1. Variables & Vectors
Variable Assignment
x <- 10 y <- 20 total <- x + yThe <- arrow binds a value in the current environment.
Pitfall: T and F are variables pre-set to TRUE/FALSE that can be overwritten: always spell TRUE and FALSE out in full.
Creating Vectors
numbers <- c(5, 10, 15, 20) names <- c("Alice", "Bob") logical_values <- c(TRUE, FALSE, TRUE)c() combines homogeneous values into an atomic vector.
Pitfall: Mixing types inside c(1, "a") silently coerces every numeric element into character strings.
Vectorized Operations
v1 <- c(1, 2, 3) doubled <- v1 * 2 # c(2, 4, 6) v2 <- c(10, 20, 30) sum_vec <- v1 + v2 # c(11, 22, 33)Math operators work element-by-element across entire vectors without loops.
Pitfall: Vector recycling silently repeats a shorter vector across a longer one when its length divides evenly.
2. Matrices & Data Frames
Matrix Creation & Access
mat <- matrix(1:6, nrow = 2, ncol = 3) val <- mat[1, 3] # Element (row 1, column 3) row1 <- mat[1, ] # Entire first row col2 <- mat[, 2] # Entire second column2D homogeneous arrays filled column-wise by default.
Pitfall: Passing values in row-major order requires byrow = TRUE, otherwise numbers fill down columns first.
Data Frame Creation & Filtering
df <- data.frame( name = c("Alice", "Bob"), grade = c(28, 24) ) grades <- df$grade good_students <- df[df$grade >= 26, ]Data Frames organize heterogeneous typed columns into tabular structures.
Pitfall: Omitting the trailing comma in df[df$grade >= 26, ] selects columns instead of filtering rows.
3. Control Flow
IF-ELSE Conditionals
score <- 75 if (score >= 60) { status <- "Pass" } else { status <- "Fail" }Standard branching over scalar logical expressions.
Pitfall: Scalar if requires a single length-1 boolean: vector conditions must use vectorized ifelse(cond, yes, no).
FOR Loop
for (i in 1:5) { print(i) } v <- c(2, 4, 6) for (val in v) { print(val * 2) }Iterates cleanly across sequences or vector items.
Pitfall: 1:length(x) loops backwards on an empty vector (c(1, 0)) — prefer seq_along(x) in robust scripts.
4. Functions & Data Analysis
Defining Functions
calculate_tax <- function(amount, rate = 0.22) { result <- amount * rate return(result) }Supports named default parameters and either explicit return() or last-expression return.
Pitfall: R uses copy-on-modify semantics: mutating a parameter inside a function does not alter the caller’s vector.
Basic Statistics & NA values
temperatures <- c(22, 25, NA, 21) mean_temp <- mean(temperatures, na.rm = TRUE) sd_temp <- sd(temperatures, na.rm = TRUE) summary_stats <- summary(temperatures)na.rm = TRUE strips missing NA values before computing summary metrics.
Pitfall: Without na.rm = TRUE, calling mean() on any dataset with even one NA returns NA.
5. Distributions & Statistical Tests
Quantiles, IQR & Reproducible Sampling
set.seed(42) samples <- rnorm(200, mean = 50, sd = 8) qs <- quantile(samples, probs = c(0.25, 0.5, 0.75)) iqr_val <- IQR(samples)set.seed() locks the RNG stream; quantile() and IQR() summarize spread robustly against outliers.
Pitfall: Skipping set.seed() before rnorm() or sample() makes analyses and unit checks non-reproducible.
Welch t-test, Correlation & Chi-Square
t_res <- t.test(group_a, group_b) cor_res <- cor.test(x, y, method = "pearson") chi_res <- chisq.test(table(channel, converted))t.test() defaults to Welch two-sample comparison (unequal variances); table() + chisq.test() checks categorical independence.
Pitfall: High Pearson r or p < 0.05 never proves causation: inspect confounders, non-linearity, and sample size.
6. Linear Regression lm() & Diagnostics
Fitting lm(), summary() & Predictions
fit <- lm(score ~ hours + study_mode, data = train_df) summary(fit)$r.squared preds <- predict(fit, newdata = test_df, interval = "confidence")Formulas like y ~ x1 + x2 handle numeric and factor predictors automatically via dummy encoding.
Pitfall: newdata column names and factor levels must match the training data frame structure.
Residuals, RMSE & Train/Test Split
set.seed(7) idx <- sample(seq_len(nrow(df)), size = floor(0.7 * nrow(df))) fit <- lm(y ~ x, data = df[idx, ]) err <- df[-idx, "y"] - predict(fit, newdata = df[-idx, ]) rmse_test <- sqrt(mean(err^2))Computing RMSE on the held-out [-idx, ] split detects overfitting better than training R² alone.
Pitfall: A single high-leverage outlier can tilt the entire OLS line: always check cooks.distance(fit).
7. Strings, Dates, Factors & Base R Pipeline
Text Cleanup, Dates & Ordered Factors
clean <- trimws(gsub("_", " ", raw_text)) days <- as.numeric(difftime(as.Date(end_d), as.Date(start_d), units = "days")) level <- factor(tier, levels = c("low", "mid", "high"), ordered = TRUE)Passing explicit levels to factor() prevents alphabetical sorting mistakes in tables and plots.
Pitfall: Calling as.numeric() directly on a factor yields internal level indices (1, 2, ...): convert with as.character() first.
Tabular Pipeline: merge() & aggregate()
joined <- merge(orders, catalog, by = "product_id") joined$revenue <- joined$qty * joined$unit_price by_cat <- aggregate(revenue ~ category, data = joined, FUN = sum)merge() + vectorized column math + aggregate() deliver a dependency-free end-to-end Base R workflow.
Pitfall: Without all.x = TRUE, merge() acts like an inner join and silently drops unmatched rows.