apply(X, MARGIN, FUN, ...)
Each section of the input array is passed as the first argument to an invocation of FUN. It is passed without a keyword modifier, so, by attaching keywords in ..., it is possible to make the array section correspond to any argument of FUN. See the examples section of lapply. The arguments to apply have unusual upper-case names to stay out of the way of names that might be used by FUN.
The sorting examples show the difference between row and column operations when the result returned by FUN is a vector. The returned value becomes the first dimension of the result, hence the transpose is necessary with row sorts.
Suppose, in the last example, that z is a 4-way array with dimension vector (2, 3, 4, 5). The expression computes the 2 by 4 matrix obtained by summing over the second and fourth extents of z (i.e., sum is called 8 times, each time on 15 values).
apply(x, 2, mean, trim=.25) # 25% trimmed column means # The result is a vector of length ncol(x)apply(z, c(1, 3), sum)
rep.int(1, nrow(x)) %*% x # faster column sum of a matrix x %*% rep.int(1, ncol(x)) # faster row sum of a matrix
apply(x, 2, sort) # sort columns of x t(apply(x, 1, sort)) # transpose result of row sort
names(dimnames(barley.exposed)) #find the names of the dimensions apply(barley.exposed, "cultivar", mean)