r - generate sets of normal distribution values within for loop -
i'm trying capture 500 samples of linear model, each sample contains 20 error terms randomly-generated values of normal distribution.
because i'm interested in results per sample, don't want generate vector of 500 * 20 = 10000 values of normal distribution.
my code is:
for (i in 1:500) { e <- rnorm(n = 20, mean = 0, sd = 4) } the problem code generates 20 values, once. each of 500 samples have same 20 error terms. how can generate 20 new values each iteration of 500-iteration for-loop?
i think confused loop doing. reassigns newly allocated random vector variable e 500 consecutive times. means every iteration e overwritten new random vector. hence, after loop finished end 1 random vector assigned e. defining e in inefficient way :)
i assume, want this:
nrsamples = 500 e <- list(mode="vector",length=nrsamples) (i in 1:nrsamples) { e[[i]] <- rnorm(n = 20, mean = 0, sd = 4) } you first define e list can contain 500 vectors. in loop random vector first created , assigned respective position in list. done 500 times each unique listindex.
you can acces random vectors follows:
> vector_1 <- e[[1]] > vector_7 <- e[[7]] > vector_1 [1] 3.8713046 3.4672930 4.2840856 4.0388847 -3.0535864 -4.1402421 -2.7912700 -1.2332116 3.2628433 3.5377208 [11] -1.0929493 0.6466984 -5.5490625 -7.3033997 1.0898727 0.2001674 2.2646435 0.1623863 2.2611607 -1.1867225 > vector_7 [1] 0.8199701 -3.1517209 -1.1319827 6.3150359 -3.7589505 1.4065123 -0.5410125 -3.0186291 6.6353592 -0.5002009 [11] -3.7416365 5.5324850 -2.2105955 -1.0931199 -2.0189795 -5.4934535 2.4210809 1.0956980 -7.6284702 -1.3574990 as can see, random vectors not identical. randomly , independently generated eachother. in order access individual elements of random vectors can this:
> vector_7[[3]] [1] -1.131983 > # or > e[[7]][[3]] [1] -1.131983
Comments
Post a Comment