mapply is a multivariate apply of sourts which applies a function in parallel over a set of arguments.
>str(mapply)
function (FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)
- FUN is a function to apply
- …contains arguments to apply over
- MoreArgs is a list of other arguments to FUN
- SIMPLIFY indicates whether the result should be simplified.
The following is tedious to type.
list(rep(1, 4), rep(2, 3), rep(3, 2), rep(4, 1)
Instead we can do
> 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 <- function(n, mean, sd) { ##创建一个函数,生成正太随机噪音,参数:观察数,平均值,标准差
+ rnorm(n, mean, sd)
+ }
> noise(5, 1, 2)
[1] 1.4930764 5.6224667 2.8635381 4.2597490 -0.1609573
> noise(1:5, 1:5, 2)
[1] 1.352830 1.310125 2.618079 1.517609 6.841648