R Built-in Functions
R ships with hundreds of built-in functions covering math, statistics, string manipulation, data structure handling, and more. These come from the base R installation — no packages needed. Knowing the most useful built-in functions saves you from writing code that already exists.
Math Functions
abs(-15) # 15 absolute value sqrt(81) # 9 square root ceiling(4.2) # 5 round up floor(4.8) # 4 round down round(3.567, 2) # 3.57 round to 2 decimal places trunc(7.9) # 7 truncate (drop decimal) exp(1) # 2.718... e to the power 1 log(100) # 4.605... natural log log10(1000) # 3 log base 10 log2(8) # 3 log base 2 factorial(6) # 720 choose(5, 2) # 10 combinations (5 choose 2)
Statistical Functions
x <- c(12, 45, 23, 67, 34, 56, 78, 29) mean(x) # 43 median(x) # 39.5 var(x) # 444.57 sd(x) # 21.08 sum(x) # 344 prod(x) # product of all values cumsum(x) # running total cumprod(x) # running product cummax(x) # running maximum cummin(x) # running minimum diff(x) # differences between consecutive pairs range(x) # c(12, 78) quantile(x, 0.25) # 1st quartile cor(x, y) # correlation coefficient
Sequence and Vector Functions
seq(1, 10, by=2) # 1 3 5 7 9
seq(0, 1, length.out=5) # 0.00 0.25 0.50 0.75 1.00
rep(c(1,2), times=3) # 1 2 1 2 1 2
rep(c(1,2), each=3) # 1 1 1 2 2 2
rev(1:5) # 5 4 3 2 1
sort(c(3,1,4,1,5)) # 1 1 3 4 5
order(c(3,1,4,1,5)) # 2 4 1 3 5 (sort indices)
unique(c(1,2,2,3,3,3)) # 1 2 3
duplicated(c(1,2,2,3)) # FALSE FALSE TRUE FALSE
table(c("A","B","A","C","B","A")) # frequency table
which(c(T,F,T,F,T)) # 1 3 5 (positions of TRUE)
String Functions
toupper("hello") # "HELLO"
tolower("WORLD") # "world"
nchar("R is great") # 10
paste("a","b","c") # "a b c"
paste0("x", 1:3) # "x1" "x2" "x3"
substr("Hello World",1,5) # "Hello"
gsub("o","0","food") # "f00d"
trimws(" hi ") # "hi"
strsplit("a,b,c",",") # list("a","b","c")
sprintf("%.2f", 3.14159) # "3.14"
Type and Check Functions
class(42L) # "integer"
typeof(3.14) # "double"
is.numeric(5) # TRUE
is.character("hi") # TRUE
is.na(NA) # TRUE
is.null(NULL) # TRUE
is.vector(c(1,2)) # TRUE
is.data.frame(df) # TRUE
exists("myvar") # TRUE/FALSE
Apply Family
sapply(1:5, sqrt) # 1.00 1.41 1.73 2.00 2.24 lapply(list(1,4,9), sqrt) # list of square roots apply(matrix(1:9,3,3), 1, sum) # row sums tapply(scores, groups, mean) # mean per group
Environment Functions
ls() # list all variables
rm(x) # remove variable x
gc() # garbage collection (free memory)
getwd() # current working directory
setwd("/path") # set working directory
system.time({ # time how long code takes
Sys.sleep(0.5)
})
Memorizing every built-in function is impossible — and unnecessary. The goal is knowing what categories of tools exist so you search for the right function when you need it. Use ?function_name for documentation and help.search("topic") to find functions by description.
