R comes with built-in functionals, of which perhaps the most well-known are the apply family of functions. Here is a description of some of the most common apply functions:
lapply()
= takes a list as an argument and applies the specified function to the list.sapply()
= the same as lapply()
but attempts to simplify the output to a vector or a matrix.
vapply()
= a variant of sapply()
in which the output object's type must be specified.mapply()
= like lapply()
but can pass multiple vectors as input to the specified function. Can be simplified like sapply()
.
Map()
is an alias to mapply()
with SIMPLIFY = FALSE
.lapply()
can be used with two different iterations:
lapply(variable, FUN)
lapply(seq_along(variable), FUN)
# Two ways of finding the mean of x
set.seed(1)
df <- data.frame(x = rnorm(25), y = rnorm(25))
lapply(df, mean)
lapply(seq_along(df), function(x) mean(df[[x]))
sapply()
will attempt to resolve its output to either a vector or a matrix.
# Two examples to show the different outputs of sapply()
sapply(letters, print) ## produces a vector
x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))
sapply(x, quantile) ## produces a matrix
mapply()
works much like lapply()
except it can take multiple vectors as input (hence the m for multivariate).
mapply(sum, 1:5, 10:6, 3) # 3 will be "recycled" by mapply