R Cheat Sheet
R is a language and environment for statistical computing and data analysis. This R cheatsheet provides an example-driven reference covering core R syntax, data structures, functions, and commonly used base R operations.
Basic Usage
print("Hello, R")
# Comment
Variables
x <- 10
y = 20
z <- x + y
Basic Types
numeric
integer
character
logical
complex
typeof(10)
typeof("text")
Vectors
v <- c(1, 2, 3)
length(v)
v[1]
v[c(1, 3)]
v + 1
Sequences
1:10
seq(0, 1, by = 0.2)
rep(1, times = 5)
Logical Operations
v > 2
v == 2
v != 1
TRUE & FALSE
TRUE | FALSE
!TRUE
Control Flow
if / else
if (x > 10) {
"large"
} else {
"small"
}
for
for (i in 1:5) {
print(i)
}
while
while (x > 0) {
x <- x - 1
}
Functions
add <- function(a, b) {
a + b
}
add(2, 3)
Default Arguments
power <- function(x, p = 2) {
x ^ p
}
Anonymous Functions
(function(x) x * x)(5)
Data Frames
df <- data.frame(
name = c("A", "B"),
age = c(20, 30)
)
df$name
df[1, ]
df[, "age"]
Factors
f <- factor(c("low", "high", "low"))
levels(f)
Lists
lst <- list(
a = 1,
b = "text",
c = TRUE
)
lst$a
lst[[2]]
Matrices
m <- matrix(1:6, nrow = 2)
m[1, 2]
dim(m)
Apply Family
apply(m, 1, sum)
apply(m, 2, mean)
lapply(lst, length)
sapply(lst, length)
Sorting
sort(v)
order(v)
Subsetting
v[v > 2]
df[df$age > 20, ]
Missing Values
NA
is.na(v)
na.omit(c(1, NA, 3))
String Functions
paste("Hello", "World")
paste0("A", "B")
substr("abcdef", 1, 3)
nchar("text")
Dates
Sys.Date()
Sys.time()
as.Date("2025-01-01")
Math Functions
sum(v)
mean(v)
median(v)
sd(v)
round(3.14159, 2)
Random Numbers
runif(5)
rnorm(5)
set.seed(123)
File I/O
write.csv(df, "data.csv")
read.csv("data.csv")
Packages
install.packages("ggplot2")
library(ggplot2)
Help & Documentation
?mean
help(sum)