The apply() family pertains to the R base package and is
populated with functions to manipulate slices of data
from matrices, arrays, lists and dataframes in a repetitive way.
These functions allow crossing the data in a number of ways and
avoid explicit use of loop constructs. They act on an input list,
matrix or array and apply a named function with one or several optional
arguments.
family is made up of the apply(), lapply() , sapply(), vapply(), mapply(),
rapply(), and tapply() functions.
> x<-matrix(1:9,nrow=3)
> x
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
>
> apply(x,1,sum)
[1] 12 15 18
> apply(x,2,sum)
[1] 6 15 24
The lapply() Function
-----------------------
You want to apply a given function to every element of a list
and obtain a list as result.
> a<-matrix(1:9,nrow=3)
> b<-matrix(10:18,nrow=3)
> c<-matrix(19:27,nrow=3)
> MyList<-list(a,b,c)
> MyList
[[1]]
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[[2]]
[,1] [,2] [,3]
[1,] 10 13 16
[2,] 11 14 17
[3,] 12 15 18
[[3]]
[,1] [,2] [,3]
[1,] 19 22 25
[2,] 20 23 26
[3,] 21 24 27
> lapply(MyList,"[",,1)
[[1]]
[1] 1 2 3
[[2]]
[1] 10 11 12
[[3]]
[1] 19 20 21
> lapply(MyList,"[",,2)
[[1]]
[1] 4 5 6
[[2]]
[1] 13 14 15
[[3]]
[1] 22 23 24
> lapply(MyList,"[",1,)
[[1]]
[1] 1 4 7
[[2]]
[1] 10 13 16
[[3]]
[1] 19 22 25
The sapply() Function
--------------------------
The sapply() function works like lapply(), but it tries to simplify
the output to the most elementary data structure that is possible.
And indeed, sapply() is a ‘wrapper’ function for lapply().
> sapply(MyList,"[",1,)
[,1] [,2] [,3]
[1,] 1 10 19
[2,] 4 13 22
[3,] 7 16 25
The mapply() Function
------------------------------
The mapply() function stands for ‘multivariate’ apply. Its purpose is
to be able to vectorize arguments to a function that is not usually
accepting vectors as arguments.
In short, mapply() applies a Function to Multiple List or multiple Vector Arguments.
The Sweep() Function
----------------------
The sweep() function is probably the closest to the apply() family.
You use it when you want to replicate different actions on the MARGIN elements