为了执行蒙特卡罗模拟,我想要5000个二项式和正态分布的样本,具有不同的样本大小(20、30和50(。我的代码可以很好地处理正态分布(以及我测试的其他分布(,但不能处理二项式分布。上面说我没有具体说明问题的论点,但我说了。
它给了我这个错误:
Error in x(n, ...) : argument "prob" is missing, with no default
我的代码是:
distribuicoes <- list(normal = c(rnorm, c(mean = 0, sd=1)),
binomial = c(rbinom, c(size = 4, prob = 0.5)))
M <- 5000
as <- function(x,n,...){x(n,...)}
for (j in c(20,30,50)){
dados <- lapply( distribuicoes, function(FUN,M){replicate(M,as(FUN[[1]],FUN[[2]],n=j))},M)
}
这是我在stackoverflow的第一个问题,如果我解释得不够好,请告诉我,我会纠正的。谢谢。
您的代码有一些错误。首先,分配给dados
只会保存for
循环中的最后一次迭代。因此,如果您想保留所有迭代,最好将其定义为一个列表,然后使用[[]]
将结果分配给每个元素。其次(这就是出现错误的原因(,您没有正确地将命名参数传递给每个函数调用(rnorm
、rbinom
(。第三,我认为最好将您的数据命名如下:
distribuicoes <- list(normal = list(dst=rnorm, args=list(mean=0, sd=1)),
binomial=list(dst=rbinom, args=list(size=4, prob=0.5)))
然后as
函数应该使用do.call
,将...
参数列表与n
组合在一个命名列表中。
as <- function(x, n, ...){
args <- as.list(c(n=n, unlist(list(...))))
do.call(x, args)
}
这是最后的代码。用5000 替换M
set.seed(123) # remove this later, just for reproducibility here.
M <- 3 # just to see how the output looks.
n <- c(2,3,5) # to show easily on the screen. Replace with your sizes.
dados <- vector("list", length(n))
for(j in seq_along(n)) {
dados[[j]] <- lapply(distribuicoes, function(f) {
replicate(M, as(x=f$dst, n=n[j], f$args)) } )
}
dados
[[1]]
[[1]]$normal
[,1] [,2] [,3]
[1,] -0.5605 1.55871 0.1293
[2,] -0.2302 0.07051 1.7151
[[1]]$binomial
[,1] [,2] [,3]
[1,] 2 1 1
[2,] 2 3 0
[[2]]
[[2]]$normal
[,1] [,2] [,3]
[1,] -0.4457 0.4008 1.7869
[2,] 1.2241 0.1107 0.4979
[3,] 0.3598 -0.5558 -1.9666
[[2]]$binomial
[,1] [,2] [,3]
[1,] 3 1 2
[2,] 1 1 2
[3,] 2 2 1
[[3]]
[[3]]$normal
[,1] [,2] [,3]
[1,] -1.08570 -0.8185 -0.1294
[2,] -0.08542 0.6849 0.8867
[3,] 1.07061 -0.3201 -0.1514
[4,] -0.14539 -1.3115 0.3298
[5,] -1.16554 -0.5996 -3.2273
[[3]]$binomial
[,1] [,2] [,3]
[1,] 1 1 2
[2,] 2 2 4
[3,] 2 2 3
[4,] 2 3 3
[5,] 1 1 1
为什么不简化流程,例如:
lapply(c(20, 30, 50), function(x) list(
norm=replicate(M, rnorm(x, mean = 0, sd=1)),
binom=replicate(M, rbinom(x, size = 4, prob = 0.5))))
这为每个rnorm和rbinom提供了3个列表(n分别为20、30和50(。