使用R中的lapply生成具有不同参数的随机数

stu*_*123 2 simulation r lapply

我需要生成具有不同参数的随机数(二项式).我试图使用lapply函数来做到这一点.

到目前为止这是我的代码:

lst1 <- list(n=c(10,20), size=c(100,200), q=c(0.1,0.2)) #list of variables

lapply(lst1, function(x) {
  rbinom(x[1],x[2],x[3])
})
Run Code Online (Sandbox Code Playgroud)

似乎有错误.

然后我也尝试了这种方式,

lapply(lst1, function(x) {
  rbinom(x$n,x$size,x$q)
})
Run Code Online (Sandbox Code Playgroud)

我仍然收到错误.任何人都可以帮我弄清楚错误吗?

谢谢.

Kar*_*ius 6

最好使用Map而不是lapply每次函数需要获取不同的参数集时:

> Map(rbinom, lst1$n, lst1$size, lst1$q)
[[1]]
 [1] 15  7  8 12  9 11  4  9 12  7

[[2]]
 [1] 47 40 37 54 40 39 39 43 50 33 34 37 42 31 26 34 31 38 43 43
Run Code Online (Sandbox Code Playgroud)

有了lapply你可以做这样的:

lapply(1:2, function(ind) rbinom(lst1$n[ind], lst1$size[ind], lst1$q[ind]))
[[1]]
 [1] 10 18  7  9  9 18  7  8  8 10

[[2]]
 [1] 46 42 44 37 38 40 52 44 42 38 40 35 41 46 44 38 41 32 61 33
Run Code Online (Sandbox Code Playgroud)