问题
Suppose I want to simulate 10 observations from lognormal distribution and repeat this 100 times. I wrote some R code, but for some reason it's not working. Here is the code:
for(i in 1:100)
{
x = rlnorm(10, meanlog = 0, sdlog = 1)
}
Any thoughts?
回答1:
This could work:
lapply(1:100, function(i) rlnorm(10, meanlog = 0, sdlog = 1))
EDIT
To calculate the mean and sd use:
lapply(1:100, function(i) {
x <- rlnorm(10, meanlog = 0, sdlog = 1)
c(mean=mean(x), sd=sd(x))
})
Or to return it in a matrix format (use do.call
):
do.call(rbind, lapply(1:100, function(i) {
x <- rlnorm(10, meanlog = 0, sdlog = 1)
c(mean=mean(x), sd=sd(x))
}))
And also to make your original code work (see DWin's note) use:
x <- list()
for(i in 1:100) {
x[[i]] <- rlnorm(10, meanlog = 0, sdlog = 1)
}
来源:https://stackoverflow.com/questions/14048401/simulate-data-from-lognormal-in-r