Introduction To The R Language Introduction To The R Language
Introduction To The R Language Introduction To The R Language
apply
apply is used to a evaluate a function (often an anonymous one) over the margins of an array.
2/7
apply
> str(apply)
function (X, MARGIN, FUN, ...)
X is an array
MARGIN is an integer vector indicating which margins should be retained.
FUN is a function to be applied
... is for other arguments to be passed to FUN
3/7
apply
> x <- matrix(rnorm(200), 20, 10)
> apply(x, 2, mean)
[1] 0.04868268 0.35743615 -0.09104379
[4] -0.05381370 -0.16552070 -0.18192493
[7] 0.10285727 0.36519270 0.14898850
[10] 0.26767260
> apply(x, 1, sum)
[1] -1.94843314 2.60601195 1.51772391
[4] -2.80386816 3.73728682 -1.69371360
[7] 0.02359932 3.91874808 -2.39902859
[10] 0.48685925 -1.77576824 -3.34016277
[13] 4.04101009 0.46515429 1.83687755
[16] 4.36744690 2.21993789 2.60983764
[19] -1.48607630 3.58709251
4/7
5/7
6/7
apply
Average matrix in an array
> a <- array(rnorm(2 * 2 * 10), c(2, 2, 10))
> apply(a, c(1, 2), mean)
[,1]
[,2]
[1,] -0.2353245 -0.03980211
[2,] -0.3339748 0.04364908
> rowMeans(a, dims = 2)
[,1]
[,2]
[1,] -0.2353245 -0.03980211
[2,] -0.3339748 0.04364908
7/7