TExcelTAD
Home › R › R Apply Family

R Apply Family

Instead of writing a loop, R programmers usually reach for the apply family: functions that call another function on every element, row, column or group. They make code shorter and state the intent clearly: "apply this to each of those".

Function Input Output
lapply(x, f) vector or list always a list
sapply(x, f) vector or list simplified to a vector/matrix when possible
vapply(x, f, FUN.VALUE) vector or list vector of a declared type (safest)
mapply(f, x, y) several vectors applies f to x[1], y[1], then x[2], y[2]…
apply(m, MARGIN, f) matrix or array over rows (1) or columns (2)
tapply(x, group, f) vector + grouping factor one result per group

lapply()

lapply() returns a list the same length as the input:

r · try it yourself
words <- list(a = "apple", b = "kiwi", c = "banana")
lapply(words, nchar)
$a
[1] 5

$b
[1] 4

$c
[1] 6

sapply()

sapply() does the same, then simplifies: if every result has length 1, you get a vector; if they all have the same length > 1, a matrix:

r · try it yourself
words <- c("apple", "kiwi", "banana")
sapply(words, nchar)
sapply(1:3, function(i) i^2)
sapply(c(min = 1, max = 2), function(k) k * 10)
sapply(1:3, function(i) c(i, i^2))     # a 2 x 3 matrix
 apple   kiwi banana
     5      4      6
[1] 1 4 9
min max
 10  20
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    4    9

Extra arguments after the function are passed on to it: sapply(lst, round, digits = 1).

vapply(): sapply with a guarantee

sapply() silently changes its output type depending on the data, which can break code. vapply() makes you declare what each result should be, and errors if it isn't:

r · try it yourself
vapply(mtcars[, 1:4], mean, numeric(1))
vapply(c("a", "bb"), nchar, integer(1))
vapply(list(1:2, 3:5), range, numeric(1))
      mpg       cyl      disp        hp
 20.09062   6.18750 230.72188 146.68750
 a bb
 1  2
Error in vapply(list(1:2, 3:5), range, numeric(1)) : values must be length 1,
 but FUN(X[[1]]) result is length 2

The last call fails because range() returns two values, not one. Use vapply() inside functions and packages where you need predictable output.

apply() on matrices

apply(X, MARGIN, FUN) runs FUN on each row (MARGIN = 1) or column (MARGIN = 2):

r · try it yourself
scores <- matrix(c(78, 85, 92, 64, 70, 81, 90, 88, 95), nrow = 3,
                 dimnames = list(c("Ana", "Ben", "Cai"), c("T1", "T2", "T3")))
scores
apply(scores, 1, mean)                 # per student
apply(scores, 2, max)                  # per test
apply(scores, 1, function(r) names(which.max(r)))
    T1 T2 T3
Ana 78 64 90
Ben 85 70 88
Cai 92 81 95
     Ana      Ben      Cai
77.33333 81.00000 89.33333
T1 T2 T3
92 81 95
 Ana  Ben  Cai
"T3" "T3" "T3"

mapply(): several inputs in parallel

mapply() walks over two or more vectors at the same time. Note that the function comes first:

r · try it yourself
mapply(function(name, n) paste(rep(name, n), collapse = " "),
       c("ha", "ho"), c(3, 2))
mapply(rep, 1:3, 3:1)
        ha         ho
"ha ha ha"    "ho ho"
[[1]]
[1] 1 1 1

[[2]]
[1] 2 2

[[3]]
[1] 3

R also has Map(), which is mapply() that always returns a list.

tapply() and split()

tapply() groups a vector by a factor and applies a function per group. split() + sapply() does the same in two steps and works for data frames too:

r · try it yourself
tapply(iris$Sepal.Length, iris$Species, median)
parts <- split(mtcars$mpg, mtcars$gear)
sapply(parts, function(v) round(mean(v), 1))
sapply(split(mtcars, mtcars$cyl), nrow)
    setosa versicolor  virginica
       5.0        5.9        6.5
   3    4    5
16.1 24.5 21.4
 4  6  8
11  7 14

Functional helpers: Filter, Reduce

Base R also includes Filter() (keep elements where a function returns TRUE) and Reduce() (combine elements pairwise):

r · try it yourself
Filter(function(n) n %% 2 == 0, 1:10)
Reduce(`+`, 1:5, accumulate = TRUE)
Reduce(function(a, b) paste0(b, a), strsplit("stressed", "")[[1]])
[1]  2  4  6  8 10
[1]  1  3  6 10 15
[1] "desserts"

Test yourself

What does lapply() always return?

  1. A vector
  2. A list
  3. A matrix
  4. A data frame

In apply(m, 2, sum), what does 2 mean?

  1. Sum twice
  2. Apply over columns
  3. Apply over rows
  4. Use 2 cores

Why prefer vapply() over sapply() in a package?

  1. It is shorter
  2. It guarantees the type and length of each result
  3. It runs in parallel
  4. It returns a list