# R语言与生信应用24-R语法-mapply

## mapply

`mapply` 称为多变量（multivariate）apply可以接收指定函数的一组参数并行计算。

``````> str(mapply)
function (FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)
``````
• `FUN` 是用来批处理的函数
• ... 用来批处理的参数
• `MoreArgs``FUN`函数的其他参数
• `SIMPLIFY` 设置是否简化参数

`list(rep(1, 4), rep(2, 3), rep(3, 2), rep(4, 1))`

``````> mapply(rep, 1:4, 4:1)
[[1]]
[1] 1 1 1 1

[[2]]
[1] 2 2 2

[[3]]
[1] 3 3

[[4]]
[1] 4
``````

## 函数的向量化操作

``````# 声明一个函数noise
> noise <- function(n, mean, sd) {
rnorm(n, mean, sd)
}
# 使用单个参数操作
> noise(5, 1, 2)
[1]  0.1629689  2.0816275  2.4775372 -0.9368394  0.9255463
# 使用多个参数操作，结果不是预期的
> noise(1:5, 1:5, 2)
[1] 1.643462 2.794333 2.914787 5.082487 5.377841
``````

## 向量化操作

``````> mapply(noise, 1:5, 1:5, 2)
[[1]]
[1] 2.591011

[[2]]
[1] 1.851819 1.861633

[[3]]
[1] 2.7667496 0.4649369 5.8556238

[[4]]
[1] 5.275667 2.682882 4.043813 4.366316

[[5]]
[1] 6.257788 3.618693 4.407559 6.736056 6.720434

``````

``````list(noise(1, 1, 2), noise(2, 2, 2),
noise(3, 3, 2), noise(4, 4, 2),
noise(5, 5, 2))
``````

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