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

generate random number with varying parameters using lapply in R

我需要生成具有不同参数的随机数(二项式)。 我正在尝试使用 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])
})

似乎有错误。

那我也试了这个方法,

lapply(lst1, function(x) {
  rbinom(x$n,x$size,x$q)
})

我仍然遇到错误。 谁能帮我找出错误?

谢谢。

当函数每次需要获取一组不同的参数时,最好使用 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

使用 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

或者在 list 的名称与函数参数匹配后使用 purrr 中的 pmap

names(formals(rbinom))
#[1] "n"    "size" "prob"

这里的'q'可以重命名为'prob'

library(purrr)
names(lst1)[3] <- 'prob'
pmap(lst1, rbinom)
#[[1]]
# [1] 13  9 12 19 11  8 14 13 16  7

#[[2]]
# [1] 42 52 37 48 41 33 34 31 47 41 41 40 39 42 41 41 52 47 42 49