The apply Family
The apply family isn't magically faster than well-written loops, but it is more concise and expressive.
apply(X, MARGIN, FUN) vector/matrix (by rows 1 or columns 2) lapply(X, FUN) sapply(X, FUN) simplified vector/matrix vapply(X, FUN, FUN.VALUE) mapply(FUN,...) / Map() tapply(X, INDEX, FUN) vector + groups outer, sweep, aggregate, by
The apply family isn't magically faster than well-written loops, but it is more concise and expressive. In the tidyverse, purrr (§20) provides a consistent alternative.
m <- matrix(1:6, 2)
apply(m, 1, sum) # row sums
apply(m, 2, function(col) col / max(col))
sapply(mtcars, mean) # mean of every column
vapply(mtcars, function(x) sum(is.na(x)), integer(1))
tapply(mtcars$mpg, mtcars$cyl, mean) # mean mpg by cylinders
mapply(function(x, y) x + y, 1:3, 4:6) # 5 7 9
Map(function(n, v) paste(n, v), c("a", "b"), c(1, 2))
sweep(m, 2, colMeans(m)) # center columns
by(mtcars, mtcars$am, function(d) mean(d$mpg))