# apply

`apply` 对数组或矩阵执行指定的函数（通常是匿名函数）。

• 通常对矩阵的一行或一列操作
• 对一组数进行操作，如计算矩阵的行平均值或列平均值。
• 不一定比循环快，但只要一行。

``````> str(apply)
function (X, MARGIN, FUN, ...)
``````
• `X` 是一个数组
• `MARGIN` 是整数型向量，指定对哪一维（如矩阵的行或列）进行操作。
• `FUN` 是用哪个函数进行操作
• ... 是传递给 `FUN` 的其他参数

``````> x <- matrix(rnorm(200), 20, 10)
> apply(x, 2, mean)
[1]  0.167162527 -0.079293974 -0.062300596 -0.328406829  0.290078933
[6]  0.480642185  0.009369719 -0.018753792  0.194263160 -0.042819273
> apply(x, 1, sum)
[1] -0.6314381  1.3082838 -0.9322577  9.2538844 -6.0182467  4.2462860
[7]  1.3619095 -1.6376867 -2.0452763 -3.1957812 -2.6102388  3.8403223
[13] -1.0428887  3.0235110  1.1093232  3.0340000  0.5430936  1.1590106
[19]  0.4819350  0.9510959
``````

## 列/行求和与平均值

• `rowSums` = `apply(x, 1, sum)`
• `rowMeans` = `apply(x, 1, mean)`
• `colSums` = `apply(x, 2, sum)`
• `colMeans` = `apply(x, 2, mean)`

## 其他使用apply的方法

``````> x <- matrix(rnorm(200), 20, 10)
> apply(x, 1, quantile, probs = c(0.25, 0.75))
[,1]      [,2]       [,3]      [,4]       [,5]       [,6]       [,7]
25% 0.09678483 -1.252172 -0.5594222 0.3003727 -0.5394311 -0.7213852 -0.6946071
75% 1.21133570  1.125509  0.4887024 1.2867236  0.4701446  0.3500056  0.1762477
[,8]       [,9]      [,10]     [,11]      [,12]      [,13]     [,14]
25% -0.2561037 -0.2304411 -0.9268922 -1.079129 -0.7953414 -0.4770530 -0.379590
75%  0.6587894  1.5569296  1.2895396  1.142885 -0.1241847  0.7192662  0.545214
[,15]      [,16]      [,17]      [,18]      [,19]      [,20]
25% -0.008474735 -0.3288624 -0.5923715 -0.3822122 -0.6172781 -1.2056816
75%  0.998829133  1.0367678  0.8497671  0.6897986  0.3691122  0.1918069
``````

``````> a <- array(rnorm(2 * 2 * 10), c(2, 2, 10))
> apply(a, c(1, 2), mean)
[,1]       [,2]
[1,] 0.006563965 -0.4093383
[2,] 0.057019258  0.1777483
> rowMeans(a, dims = 2)
[,1]       [,2]
[1,] 0.006563965 -0.4093383
[2,] 0.057019258  0.1777483
``````

https://mp.weixin.qq.com/s/E9ykuIbc-2Ja9HOY0bn_6g
B站公益74小时生信工程师教学视频合辑
https://mp.weixin.qq.com/s/IyFK7l_WBAiUgqQi8O7Hxw

https://mp.weixin.qq.com/s/KgbilzXnFjbKKunuw7NVfw