# Grouping functions in base R

### Likan Zhan · 2017-02-16

R has many *apply functions which are ably described in the help files (e.g. ?apply). There are enough of them, though, that beginning useRs may have difficulty deciding which one is appropriate for their situation or even remembering them all. They may have a general sense that “I should be using an *apply function here”, but it can be tough to keep them all straight at first.

Despite the fact (noted in other answers) that much of the functionality of the *apply family is covered by the extremely popular plyr package, the base functions remain useful and worth knowing.

This answer is intended to act as a sort of signpost for new useRs to help direct them to the correct *apply function for their particular problem. Note, this is not intended to simply regurgitate or replace the R documentation! The hope is that this answer helps you to decide which *apply function suits your situation and then it is up to you to research it further. With one exception, performance differences will not be addressed.

# 1. apply

When you want to apply a function to the rows or columns of a matrix (and higher-dimensional analogues); not generally advisable for data frames as it will coerce to a matrix first.

1. Create a two dimensional matrix
M <- matrix(seq(1, 16), 4, 4)
M
##      [,1] [,2] [,3] [,4]
## [1,]    1    5    9   13
## [2,]    2    6   10   14
## [3,]    3    7   11   15
## [4,]    4    8   12   16

Apply min to rows

apply(M, 1, min)
##  1 2 3 4

Apply max to columns

apply(M, 2, max)
##   4  8 12 16
1. Create a three dimensional array
M <- array(seq(32), dim = c(4,4,2))
M
## , , 1
##
##      [,1] [,2] [,3] [,4]
## [1,]    1    5    9   13
## [2,]    2    6   10   14
## [3,]    3    7   11   15
## [4,]    4    8   12   16
##
## , , 2
##
##      [,1] [,2] [,3] [,4]
## [1,]   17   21   25   29
## [2,]   18   22   26   30
## [3,]   19   23   27   31
## [4,]   20   24   28   32

Apply sum across each M[*, , ] - i.e Sum across 2nd and 3rd dimension, and the result is one-dimensional

apply(M, 1, sum)
##  120 128 136 144

Apply sum across each M[*,*, ] - i.e Sum across 3rd dimension, and the result is two-dimensional

apply(M, c(1, 2), sum)
##      [,1] [,2] [,3] [,4]
## [1,]   18   26   34   42
## [2,]   20   28   36   44
## [3,]   22   30   38   46
## [4,]   24   32   40   48

Furthermore, if you want row/column means or sums for a 2D matrix, be sure to investigate the highly optimized, lightning-quick colMeans, rowMeans, colSums, rowSums.

# 2. lapply

Use this function when you want to apply a function to each element of a list in turn and get a list back.

This is the workhorse of many of the other *apply functions. Peel back their code and you will often find lapply underneath.

x <- list(a = 1, b = 1:3, c = 10:100)
x
## $a ##  1 ## ##$b
##  1 2 3
##
## $c ##  10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ##  27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 ##  44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 ##  61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 ##  78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 ##  95 96 97 98 99 100 lapply(x, FUN = length) ##$a
##  1
##
## $b ##  3 ## ##$c
##  91
lapply(x, FUN = sum)
## $a ##  1 ## ##$b
##  6
##
## $c ##  5005 # 3. sapply When you want to apply a function to each element of a list in turn, but you want a vector back, rather than a list. If you find yourself typing unlist(lapply(...)), stop and consider sapply. x <- list(a = 1, b = 1:3, c = 10:100) x ##$a
##  1
##
## $b ##  1 2 3 ## ##$c
##    10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
##   27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43
##   44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60
##   61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77
##   78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94
##   95  96  97  98  99 100

Compare with above; a neamed vector, not a list

sapply(x, FUN = length)
##  a  b  c
##  1  3 91
sapply(x, FUN = sum)
##    a    b    c
##    1    6 5005

In more advanced uses of sapply it will attempt to coerce the result to a multi-dimensional array, if appropriate. For example, if our function returns vectors of the same length, sapply will use them as columns of a matrix:

sapply(1:5, function(x) rnorm(3, x))
##           [,1]     [,2]     [,3]     [,4]     [,5]
## [1,] 0.7150441 1.541538 2.826377 2.189904 5.445851
## [2,] 0.8967333 1.740967 3.521810 4.947470 5.302142
## [3,] 2.5446347 0.993315 1.929353 5.329138 6.349682

If our function returns a 2 dimensional matrix, sapply will do essentially the same thing, treating each returned matrix as a single long vector:

sapply(1:5, function(x) matrix(x, 2, 2))
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    2    3    4    5
## [2,]    1    2    3    4    5
## [3,]    1    2    3    4    5
## [4,]    1    2    3    4    5

Unless we specify simplify = "array", in which case it will use the individual matrices to build a multi-dimensional array:

sapply(1:5, function(x) matrix(x, 2, 2), simplify = "array")
## , , 1
##
##      [,1] [,2]
## [1,]    1    1
## [2,]    1    1
##
## , , 2
##
##      [,1] [,2]
## [1,]    2    2
## [2,]    2    2
##
## , , 3
##
##      [,1] [,2]
## [1,]    3    3
## [2,]    3    3
##
## , , 4
##
##      [,1] [,2]
## [1,]    4    4
## [2,]    4    4
##
## , , 5
##
##      [,1] [,2]
## [1,]    5    5
## [2,]    5    5

Each of these behaviors is of course contingent on our function returning vectors or matrices of the same length or dimension.

# 4. vapply

When you want to use sapply but perhaps need to squeeze some more speed out of your code.

For vapply, you basically give R an example of what sort of thing your function will return, which can save some time coercing returned values to fit in a single atomic vector.

x <- list(a = 1, b = 1:3, c = 10:100)
x
## $a ##  1 ## ##$b
##  1 2 3
##
## $c ##  10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ##  27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 ##  44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 ##  61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 ##  78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 ##  95 96 97 98 99 100 Note that since the advantage here is mainly speed, this example is only for illustration. We’re telling R that everything returned by length() should be an integer of length 1. vapply(x, FUN = length, FUN.VALUE = 0L) ## a b c ## 1 3 91 # 5. mapply For when you have several data structures (e.g. vectors, lists) and you want to apply a function to the 1st elements of each, and then the 2nd elements of each, etc., coercing the result to a vector/array as in sapply. This is multivariate in the sense that your function must accept multiple arguments. Sums the 1st elements, the 2nd elements, etc. mapply(sum, 1:5, 1:5, 1:5) ##  3 6 9 12 15 To do rep(1, 4), rep(2, 3), etc. mapply(rep, 1:4, 4:1) ## [] ##  1 1 1 1 ## ## [] ##  2 2 2 ## ## [] ##  3 3 ## ## [] ##  4 # 6. Map A wrapper to mapply with SIMPLIFY = FALSE, so it is guaranteed to return a list. Map(sum, 1:5, 1:5, 1:5) ## [] ##  3 ## ## [] ##  6 ## ## [] ##  9 ## ## [] ##  12 ## ## [] ##  15 # 7. rapply For when you want to apply a function to each element of a nested list structure, recursively. To give you some idea of how uncommon rapply is, I forgot about it when first posting this answer! Obviously, I’m sure many people use it, but YMMV. rapply is best illustrated with a user-defined function to apply: Define a nested list stucture l <- list(a = list(a1 = "Boo", b1 = 2, c1 = "Eeek"), b = 3, c = "Yikes", d = list(a2 = 1, b2 = list(a3 = "Hey", b3 = 5))) l ##$a
## $a$a1
##  "Boo"
##
## $a$b1
##  2
##
## $a$c1
##  "Eeek"
##
##
## $b ##  3 ## ##$c
##  "Yikes"
##
## $d ##$d$a2 ##  1 ## ##$d$b2 ##$d$b2$a3
##  "Hey"
##
## $d$b2$b3 ##  5 Define a function. note to append ! to string, otherwise increment myFun <- function(x){ if (is.character(x)){ return(paste(x,"!",sep="")) } else{ return(x + 1) } } Result is named vector, coerced to character rapply(l, myFun) ## a.a1 a.b1 a.c1 b c d.a2 d.b2.a3 d.b2.b3 ## "Boo!" "3" "Eeek!" "4" "Yikes!" "2" "Hey!" "6" Result is a nested list like l, with values altered rapply(l, myFun, how = "replace") ##$a
## $a$a1
##  "Boo!"
##
## $a$b1
##  3
##
## $a$c1
##  "Eeek!"
##
##
## $b ##  4 ## ##$c
##  "Yikes!"
##
## $d ##$d$a2 ##  2 ## ##$d$b2 ##$d$b2$a3
##  "Hey!"
##
## $d$b2\$b3
##  6

# 8. tapply

For when you want to apply a function to subsets of a vector and the subsets are defined by some other vector, usually a factor.

The black sheep of the *apply family, of sorts. The help file’s use of the phrase “ragged array” can be a bit confusing, but it is actually quite simple.

Define a vector

x <- 1:20
x
##    1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

A factor (of the same length!) defining groups:

y <- factor(rep(letters[1:5], each = 4))
y
##   a a a a b b b b c c c c d d d d e e e e
## Levels: a b c d e

Add up the values in x within each subgroup defined by y:

tapply(x, y, sum)
##  a  b  c  d  e
## 10 26 42 58 74

More complex examples can be handled where the subgroups are defined by the unique combinations of a list of several factors. tapply is similar in spirit to the split-apply-combine functions that are common in R (aggregate, by, ave, ddply`, etc.) Hence its black sheep status.