Apply Functions Over Array Margins
Returns a vector or array or list of values obtained by applying a function to margins of an array or matrix.
apply(X, MARGIN, FUN, ...)
- an array, including a matrix.
- a vector giving the subscripts which the function will
be applied over. E.g., for a matrix
c(1, 2)indicates rows and columns. Where
Xhas named dimnames, it can be a character vector selecting dimension names.
- the function to be applied: see Details.
In the case of functions like
%*%, etc., the function name must be backquoted or quoted.
- optional arguments to
X is not an array but an object of a class with a non-null
dim value (such as a data frame),
to coerce it to an array via
as.matrix if it is two-dimensional
(e.g., a data frame) or via
FUN is found by a call to
match.fun and typically
is either a function or a symbol (e.g. a backquoted name) or a
character string specifying a function to be searched for from the
environment of the call to
... cannot have the same name as any of the
other arguments, and care may be needed to avoid partial matching to
FUN. In general-purpose code it is good
practice to name the first three arguments if
... is passed
through: this both avoids partial matching to
FUN and ensures that a sensible error message is given if
FUN are passed
If each call to
FUNreturns a vector of length
applyreturns an array of dimension
n > 1. If
applyreturns a vector if
MARGINhas length 1 and an array of dimension
0, the result has length 0 but not necessarily the correct dimension.If the calls to
FUNreturn vectors of different lengths,
applyreturns a list of length
MARGINif this has length greater than one.In all cases the result is coerced by
as.vectorto one of the basic vector types before the dimensions are set, so that (for example) factor results will be coerced to a character array.
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.
## Compute row and column sums for a matrix: x <- cbind(x1 = 3, x2 = c(4:1, 2:5)) dimnames(x)[] <- letters[1:8] apply(x, 2, mean, trim = .2) col.sums <- apply(x, 2, sum) row.sums <- apply(x, 1, sum) rbind(cbind(x, Rtot = row.sums), Ctot = c(col.sums, sum(col.sums))) stopifnot( apply(x, 2, is.vector)) ## Sort the columns of a matrix apply(x, 2, sort) ##- function with extra args: cave <- function(x, c1, c2) c(mean(x[c1]), mean(x[c2])) apply(x, 1, cave, c1 = "x1", c2 = c("x1","x2")) ma <- matrix(c(1:4, 1, 6:8), nrow = 2) ma apply(ma, 1, table) #--> a list of length 2 apply(ma, 1, stats::quantile) # 5 x n matrix with rownames stopifnot(dim(ma) == dim(apply(ma, 1:2, sum))) ## Example with different lengths for each call z <- array(1:24, dim = 2:4) zseq <- apply(z, 1:2, function(x) seq_len(max(x))) zseq ## a 2 x 3 matrix typeof(zseq) ## list dim(zseq) ## 2 3 zseq[1,] apply(z, 3, function(x) seq_len(max(x))) # a list without a dim attribute