R Quick Reference
Everything you need day‑to‑day – data science, statistics, and visualisation.
Basic Syntax
# Comments start with # x <- 5 # Assignment (preferred) y = 10 # Also valid z <- x + y # Arithmetic # Print to console print(z) print("Hello, World!") # Functions sum(1, 2, 3) # 6 sqrt(16) # 4 abs(-5) # 5
Data Types
Basic Types
numeric– 42, 3.14integer– 42Lcharacter– "hello"logical– TRUE, FALSEfactor– categorical datacomplex– 1 + 2iraw– raw bytes
Data Structures
vector– c(1, 2, 3)matrix– matrix(1:6, nrow=2)array– multi‑dimensionallist– list(a=1, b="x")data.frame– data.frame(x=1:3, y=c("a","b","c"))tibble– modern data.frame (tibble)
Type Checking
class(x) # class of object typeof(x) # internal type is.numeric(x) # TRUE/FALSE is.character(x) is.logical(x) is.na(x) # check for NA is.null(x) # check for NULL
Vectors
# Create vectors v <- c(1, 2, 3, 4, 5) v <- 1:5 # sequence v <- seq(1, 10, 2) # 1, 3, 5, 7, 9 # Named vectors v <- c(a=1, b=2, c=3) # Access v[1] # first element v[1:3] # first 3 v[-1] # all except first v["a"] # by name # Vector operations (element‑wise) v + 1 v * 2 v > 3 v[v > 2] # filtering # Common functions length(v) # number of elements sum(v) # sum mean(v) # mean median(v) # median sd(v) # standard deviation var(v) # variance min(v) / max(v) # min / max sort(v) # sorted rev(v) # reversed unique(v) # unique values
Matrices
# Create matrix m <- matrix(1:9, nrow=3, ncol=3) m <- matrix(1:9, nrow=3, byrow=TRUE) # Access m[2, 3] # row 2, col 3 m[2, ] # row 2 m[, 3] # col 3 # Matrix operations t(m) # transpose m %*% m # matrix multiplication m * m # element‑wise diag(m) # diagonal dim(m) # dimensions nrow(m) / ncol(m) # rows / columns
Lists
# Create list lst <- list(a=1, b="hello", c=c(1,2,3)) # Access lst$a # by name lst[["a"]] # by name (string) lst[[1]] # by index # Add / modify lst$d <- TRUE lst[["e"]] <- 42 # Remove lst$d <- NULL # Merge lists c(lst1, lst2)
Data Frames
# Create data frame df <- data.frame( name = c("Alice", "Bob", "Charlie"), age = c(25, 30, 35), city = c("Delhi", "Mumbai", "Bangalore"), stringsAsFactors = FALSE ) # Access df$name # column df[["name"]] # column (string) df[1, ] # row 1 df[, 2] # column 2 df[1:2, c("name", "age")] # subset # View head(df) # first 6 rows tail(df) # last 6 rows str(df) # structure summary(df) # summary statistics dim(df) # dimensions colnames(df) # column names rownames(df) # row names
Control Flow
if / else
if (x > 0) { print("positive") } else if (x == 0) { print("zero") } else { print("negative") }
for Loop
for (i in 1:5) { print(i) } # Iterate over vector for (name in c("Alice", "Bob", "Charlie")) { print(paste("Hello", name)) }
while Loop
i <- 1
while (i <= 5) {
print(i)
i <- i + 1
}
repeat (infinite)
i <- 1 repeat { print(i) i <- i + 1 if (i > 5) break }
apply family
apply(matrix, 1, sum) # rows apply(matrix, 2, mean) # columns lapply(list, function) # list → list sapply(list, function) # list → vector vapply(list, function, FUN.VALUE) # typed tapply(vector, factor, mean) # group by mapply(function, ...) # multiple vectors
Functions
my_function <- function(arg1, arg2 = 10) {
result <- arg1 * arg2
return(result)
}
# Default arguments
greet <- function(name, greeting = "Hello") {
paste(greeting, name)
}
# Anonymous functions
sapply(1:5, function(x) x^2)
# Ellipsis (...)
my_sum <- function(...) {
sum(...)
}
Data Manipulation (dplyr)
Installation
install.packages("dplyr")
library(dplyr)
Common Functions
# Select columns select(df, name, age) select(df, -city) # Filter rows filter(df, age > 25) filter(df, age > 25 & city == "Delhi") # Arrange (sort) arrange(df, age) arrange(df, desc(age)) # Mutate (create new columns) mutate(df, age_sq = age^2) mutate(df, age_sq = age^2, .before = age) # Summarise summarise(df, avg_age = mean(age), count = n()) # Group by group_by(df, city) %>% summarise(avg_age = mean(age)) # Piping df %>% filter(age > 25) %>% select(name, age) %>% arrange(desc(age)) # Rename rename(df, new_name = old_name)
Tidy Data (tidyr)
# Installation install.packages("tidyr") library(tidyr) # Pivot longer (wide → long) df_long <- pivot_longer(df, cols = starts_with("col"), names_to = "key", values_to = "value") # Pivot wider (long → wide) df_wide <- pivot_wider(df_long, names_from = "key", values_from = "value") # Separate a column df <- separate(df, col, into = c("part1", "part2"), sep = "-") # Unite columns df <- unite(df, new_col, col1, col2, sep = "_") # Complete missing combinations df <- complete(df, nesting(col1), fill = list(value = 0)) # Replace NAs df <- replace_na(df, list(value = 0))
Data Visualisation (ggplot2)
Installation
install.packages("ggplot2")
library(ggplot2)
Basic Plot
# Scatter plot ggplot(df, aes(x = x, y = y)) + geom_point() # Line plot ggplot(df, aes(x = x, y = y)) + geom_line() # Bar plot ggplot(df, aes(x = category, y = value)) + geom_bar(stat = "identity") # Histogram ggplot(df, aes(x = value)) + geom_histogram(binwidth = 1) # Box plot ggplot(df, aes(x = category, y = value)) + geom_boxplot() # With colour ggplot(df, aes(x = x, y = y, colour = group)) + geom_point() # Facets ggplot(df, aes(x = x, y = y)) + geom_point() + facet_wrap(~group) # Themes ggplot(df, aes(x, y)) + geom_point() + theme_minimal() # Labels ggplot(df, aes(x, y)) + geom_point() + labs( title = "Title", x = "X‑axis", y = "Y‑axis", caption = "Source: data" )
Statistical Functions
# Descriptive statistics mean(x) # mean median(x) # median sd(x) # standard deviation var(x) # variance cor(x, y) # correlation cov(x, y) # covariance quantile(x) # quartiles summary(x) # five‑number summary # t‑test t.test(x, y) # two‑sample t.test(x, mu = 0) # one‑sample # ANOVA aov(y ~ group, data = df) # Linear regression lm(y ~ x, data = df) lm(y ~ x1 + x2, data = df) lm(y ~ ., data = df) # all variables # GLM glm(y ~ x, family = binomial, data = df) # Chi‑square test chisq.test(table(df$col1, df$col2)) # Random sampling sample(x, size = 10) sample(x, size = 10, replace = TRUE) set.seed(123) # reproducible
Common Packages
Data Manipulation
dplyr– data manipulationtidyr– tidy datatibble– modern data framesstringr– string operationsforcats– factorslubridate– date/timepurrr– functional programming
Visualisation
ggplot2– grammar of graphicsplotly– interactive plotsshiny– interactive web apps
Machine Learning
caret– classification/regressionrandomForest– random forestxgboost– gradient boostinge1071– SVM, NBglmnet– elastic net
Other
knitr– dynamic reportsrmarkdown– markdown documentsblogdown– websitesbookdown– books
Reading & Writing Data
# CSV write.csv(df, "file.csv", row.names = FALSE) df <- read.csv("file.csv") # Readr (faster, better default) library(readr) write_csv(df, "file.csv") df <- read_csv("file.csv") # Excel library(readxl) df <- read_excel("file.xlsx", sheet = 1) library(writexl) write_xlsx(df, "file.xlsx") # RDS (native R format) saveRDS(df, "file.rds") df <- readRDS("file.rds") # Feather (fast binary) library(feather) write_feather(df, "file.feather") df <- read_feather("file.feather") # JSON library(jsonlite) toJSON(df) fromJSON("file.json")
R Tips
- Use
<-for assignment (not=) – it's the R standard. - Use
tibbleoverdata.frame– better printing and handling. - Use
%>%(pipe) for readable code (frommagrittr). - Avoid
attach()– usewith()ordplyrverbs. - Use
str()to inspect any object. - Use
rm(list = ls())to clear environment. - Use
sessionInfo()to check package versions. - Use
set.seed()for reproducible results. - Use
RStudio– the best IDE for R. - Use
install.packages()for packages,library()to load.
📌 Quick Reference
Assignment:
Vectors:
Data frames:
dplyr:
ggplot2:
Apply:
Pipe:
Stats:
<- (preferred)Vectors:
c(1,2,3), access with [ ]Data frames:
data.frame(), tibble()dplyr:
select, filter, arrange, mutate, summarise, group_byggplot2:
ggplot(aes()) + geom_*Apply:
lapply, sapply, tapply, applyPipe:
%>% (from magrittr)Stats:
lm, t.test, aov, chisq.test