A function in the *apply family is an abstraction of a for loop. Compared with the for loops *apply functions have the following advantages:
However for loops are more general and can give us more control allowing to achieve complex computations that are not always trivial to do using *apply functions.
The relationship between for loops and *apply functions is explained in the documentation for for loops.
*apply FamilyThe *apply family of functions contains several variants of the same principle that differ based primarily on the kind of output they return.
| function | Input | Output |
|---|---|---|
apply | matrix, data.frame, or array | vector or matrix (depending on the length of each element returned) |
sapply | vector or list | vector or matrix (depending on the length of each element returned) |
lapply | vector or list | list |
vapply | vector or `list | vector or matrix (depending on the length of each element returned) of the user-designated class |
mapply | multiple vectors, lists or a combination | list |
See "Examples" to see how each of these functions is used.