For performing a Monte-Carlo simulation, I want 5000 samples of the binomial and the normal distributions, with different samples sizes (20,30 and 50). My code works perfectly well with the normal (and other distributions that I tested) but it doesn't with the binomial. It says that I didn't specify the prob argument, but I did.
It gives me this error:
Error in x(n, ...) : argument "prob" is missing, with no default
My code is this:
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)
}
It's my first question here in stackoverflow, if I didn't explain something well enough, please let me know and I'll correct it. Thank you.
Your code has a few errors. First, your assignment to dados
is only going to save the last iteration in the for
loop. So if you want to keep all iterations, best to define it as a list and then assign the results to each element using [[]]
. Second (and this is why you get the error), you're not correctly passing named arguments to each function call (rnorm
, rbinom
). Third, I think it's better to name your data as follows:
distribuicoes <- list(normal = list(dst=rnorm, args=list(mean=0, sd=1)),
binomial=list(dst=rbinom, args=list(size=4, prob=0.5)))
Then the as
function should use do.call
, combining the ...
argument list together with n
in one named list.
as <- function(x, n, ...){
args <- as.list(c(n=n, unlist(list(...))))
do.call(x, args)
}
So here's the final code. Replace M with 5000
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