我正在尝试生成几个随机数系列,每个系列都有一组不同的参数。然后我想复制所有这些。我想要一个函数来执行此操作,它似乎应该是一个 1-liner,类似于rnorm()
生成数字、mapply()
为多个参数集生成这些数字并replicate()
重复整个过程。
为了实现这一点,我编写了一个函数,...
我希望其参数与...
in相对应mapply
,但它似乎...
被mapply
. 我有一些示例可以阐明我想要的输出以及问题:
# Some values to be passed to the ... of mapply
mus <- c(-30, 0, 30)
sds <- c(0.1, 1, 10)
# =================================
# = What I want, if it would work =
# =================================
f <- function(n=3, ...){
replicate(2, mapply(rnorm, MoreArgs=list(n=n), ...))
}
f(mean=mus, sd=sds) # Doesn't work :(
>, , 1
>
> [,1]
>[1,] -0.4901243
>[2,] 0.8268027
>[3,] -0.4829781
>
>, , 2
>
> [,1]
>[1,] -0.02025903
>[2,] -1.57011537
>[3,] 0.49234503
# ==========================================================
# = What I can currently get to work, but not style I want =
# ==========================================================
# I can't understand why f.inside is needed!
f2 <- function(n=3, ...){
f.inside <- function() mapply(rand.gen, MoreArgs=list(n=n), ...)
replicate(2, f.inside())
}
f2(mean=mus, sd=sds) # Desired output
>, , 1
>
> [,1] [,2] [,3]
>[1,] -29.83762 -0.06138165 9.956601
>[2,] -30.04880 1.39123405 33.036675
>[3,] -29.94070 -1.15741513 19.337497
>[4,] -29.92360 0.74300731 38.741367
>[5,] -29.81723 0.84565813 22.261605
>
>, , 2
>
> [,1] [,2] [,3]
>[1,] -30.01407 -0.5198845 20.85942
>[2,] -29.77586 -0.1705062 22.06274
>[3,] -29.96901 -0.4412471 21.42849
>[4,] -30.04079 0.4230790 28.35480
>[5,] -30.04794 0.3000821 50.09012
我猜我需要把它包起来...
;我不经意地尝试了alist()
, list()
, bquote()
,expression()
和as.call()
其他几种失败的方法。
1)为什么看起来完全忽略
编辑:这是一个辅助问题,答案是“点不适用于复制”。好的,进入核心问题...mapply
了?f()
...
# =====================================
# = OK, Function for Refined Question =
# =====================================
f.edit <- function(n=3, ...){
l <- list(...)
replicate(2,mapply(rnorm, MoreArgs=list(n=n), l))
}
f.edit(mean=mus, sd=sds) # Doesn't work :(
2)如何将对象的元素拆分为 length(object) 元素,并将它们作为单独的项目传递给mapply
's ...
?
我需要在椭圆上做得更好。我真的被这个难住了。