Random sampling in nested loops

Hi!

I am new to this forum and I hope someone can help me with my code please : ) ?
My goal is:

I want to sample from a poisson-distribution, suppose lambda = 6, thats why:
qpois(runif(1), lambda) which gives me N (random) numbers.

Then what I want is to calculate the qlnorm (inverse lognormal) N-times (iteration), sum the results as one iteration and do 10,000 iterations.

From my code if I run the embedded loop (b) only, it seems that the sampling works perfectly. But if I run both loops (a and b), then my embedded loop seems to give always a value of 25 instead of randomly numbers / sampling from the poisson distribution.

here is an extract from my code, where the error occurs:

#> Code comment

nsim <- 1000
X<- matrix(ncol=1, nrow=nsim)
Y<- matrix(ncol=1, nrow=nsim)
for (a in 1:nsim){
for (b in 1:qpois(runif(1), lambda)){
  Y[b,] <- qlnorm(runif(1), meanlog = logMean, sdlog = logSd)
}
X[a,] <- sum(Y, na.rm = T)
}

I hope I could describe my problem properly and that somebody can explain to me what I am doing wrong?

With kind regards,
sam1

I solved it already! I had to clear the Y before rerun it! xD

Sorry

You don't actually need a second loop. This

for (b in 1:qpois(runif(1), lambda)){
  Y[b,] <- qlnorm(runif(1), meanlog = logMean, sdlog = logSd)
}
X[a,] <- sum(Y, na.rm = T)

could be simplified to

n  = qpois(runif(1), lambda)
Y = qlnorm(n, meanlog = logMean, sdlog = logSd)
X[a,] = sum(Y)
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.