Krina M - 3 months ago 41

R Question

I am trying to learn for loop. Below is the code. I want to simulate log normal distribution as shown below with sample size 200, and want to replicate (different results, but similar distribution with similar mean and SD) it 100 times. How do I store results in a dataframe or matrix? By below mentioned code, I am only getting results for 1st replicate (200 subjects).

Any tips will be very helpful.

Thanks,

Krina

`nRep <- 100`

result<-list()

for(i in 1:nRep) {

n<-200

cv.tumor= 0.40

sd.tumor<-sqrt(log((cv.tumor)^2+1))

Base_Tumor <- exp(rnorm(n, log(8.5), sd.tumor))

result[[i]]<-Base_Tumor

}

print(result)

Answer

Maybe you're only seeing the first 200 but the code returns all the info separated by list (with each list having 200 elements).

Anyway, with `as.data.frame(unlist(result))`

you can get a dataframe with all the results together.