説明
配列あるいは行列の周辺に関数を適用し結果として得られた値をベクトル、配列、あるいはリストとして返す。
使用法
apply(X, MARGIN, FUN, …)
引数
X 配列あるいは行列
MARGIN 関数を適用する要素の添字を与えるベクトル。[例] 行列に対しては1は行方向を、2は列方向を、c(1,2)は行および列方向を意味する。引数Xが名前付きの次元名(dimnames)を持っている場合、MARGINは次元名を選択する文字ベクトルでもよい。
FUN 周辺に対して適用する関数。+, %*%, etcなどの関数についてはヘルプの詳細を参照せよ。関数名はバッククオートもしくはクオートで囲む必要がある。
… オプショナル引数
返り値
If each call to FUN returns a vector of length n, then apply returns an array of dimension c(n, dim(X)[MARGIN]) if n > 1.
If n equals 1, apply returns a vector if MARGIN has length 1 and an array of dimension dim(X)[MARGIN] otherwise.
If n is 0, the result has length 0 but not necessarily the ‘correct’ dimension.
If the calls to FUN return vectors of different lengths, apply returns a list of length prod(dim(X)[MARGIN]) with dim set to MARGIN if this has length greater than one.
In all cases the result is coerced by as.vector to one of the basic vector types before the dimensions are set, so that (for example) factor results will be coerced to a character array.
実行例
> x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
> x
x1 x2
[1,] 3 4
[2,] 3 3
[3,] 3 2
[4,] 3 1
[5,] 3 2
[6,] 3 3
[7,] 3 4
[8,] 3 5
> apply(x,1,sum)
[1] 7 6 5 4 5 6 7 8
> apply(x,2,sum)
x1 x2
24 24
> apply(x,c(1,2),sum)
x1 x2
[1,] 3 4
[2,] 3 3
[3,] 3 2
[4,] 3 1
[5,] 3 2
[6,] 3 3
[7,] 3 4
[8,] 3 5

コメント