apply(x, margin, function, …)
apply implements a function across the rows or columns of a matrix. It also works on multidimensional arrays and can be used to apply functions across one or more dimensions of those arrays.
  • x – A matrix or array.
  • margin – The dimension of the matrix or array x to preserve. If x is an array, then this may be a vector indicating each dimension that should be preserved.
  • function – A function (e.g. mean) to be applied across each dimension not listed in margin. In a matrix, the function would be applied across the rows or columns of x, whichever dimension is not listed in the margin argument.

Example. Below a matrix with 10 rows and 2 columns is created, and we identify the sum of each column. In the second example, an array with dimensions 10x2x2 is created, and the second and third dimensions are to be preserved. Since sum is applied across only the first dimension of y, two dimensions remain in the object returned by the second apply command, i.e. a matrix is returned.
> x <- matrix(1:20, nrow=10)
> apply(x, 2, sum)
[1]  55 155
> y <- array(1:40, c(10,2,2))
> apply(y, c(2,3), sum)
     [,1] [,2]
[1,]   55  255
[2,]  155  355
Tip. Remember: The second argument of apply indicates which dimensions to preserve, and the function is applied across all the other dimensions. If you cannot remember what to put in for the margin, just run a little example to check.

Leave a Reply