apply.pdf

(73 KB) Pobierz
Introduction to the R Language
Loop Functions - apply
Roger Peng, Associate Professor
Johns Hopkins Bloomberg School of Public Health
apply
apply
is used to a evaluate a function (often an anonymous one) over the margins of an array.
·
It is most often used to apply a function to the rows or columns of a matrix
·
It can be used with general arrays, e.g. taking the average of an array of matrices
·
It is not really faster than writing a loop, but it works in one line!
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
col/row sums and means
For sums and means of matrix dimensions, we have some shortcuts.
·
rowSums
=
apply(x, 1, sum)
·
rowMeans
=
apply(x, 1, mean)
·
colSums
=
apply(x, 2, sum)
·
colMeans
=
apply(x, 2, mean)
The shortcut functions are
much
faster, but you won’t notice unless you’re using a large matrix.
5/7
Zgłoś jeśli naruszono regulamin