I am trying to run 1000 simulations from the exponential distribution in R. I hope to get a list of the simulations and a vector of their means. But when I run the code, the first 999 elements of the list are NULL and thus the first 999 means are NAs. what am I doing wrong?
nosim <- 1000
n <- 40
r<- 0.2
means<- vector()
sims <- list()
set.seed(4993)
for(i in nosim){
sims[[i]] = rexp(n, r)
}
means = sapply(sims,mean)
I think the problem is that your variable nosim
is a scalar and not an sequence/array.
You should use seq
(or the faster seq.int
) instead (as in seq(1,nosim)
):
nosim <- 1000
n <- 40
r<- 0.2
means<- vector() # not really necessary
sims <- list()
set.seed(4993)
for(i in seq(1,nosim)){ # or use `for(i in seq.int(nosim) ){`
sims[[i]] = rexp(n, r)
}
means = sapply(sims,mean)
Hope this helps