Skip to content
Prev 300531 / 398503 Next

double for cycle

First. Your example does not make sense.

for (n in 2:10) {s[n]=1+s[n]+rnorm(1,mean=0,sd=1)}

adds 1 + 1 + rnorm(1) so it will result in values ranging from 0 - 4 with a
few exceeding that range. It will never result in 9 values greater than 4.

For example I get
[1] 1.000000 3.370958 1.435302 2.363128 2.632863 2.404268 1.893875 3.511522
 [9] 1.905341 4.018424

Second. You could avoid the loop completely with
[1] 1.000000 3.370958 1.435302 2.363128 2.632863 2.404268 1.893875 3.511522
 [9] 1.905341 4.018424

I'm using set.seed(42) to generate the same set of random values to show
the two approaches give the same result. You would not generally use
set.seed() in your analysis. 

To get three sets use
[,1]       [,2]       [,3]
 [1,] 1.000000  1.0000000  1.0000000
 [2,] 3.370958  1.9372859 -0.4404669
 [3,] 1.435302  3.3048697  3.3201133
 [4,] 2.363128  4.2866454  1.6933614
 [5,] 2.632863  0.6111393  0.2186916
 [6,] 2.404268  1.7212112  1.8280826
 [7,] 1.893875  1.8666787  3.2146747
 [8,] 3.511522  2.6359504  3.8951935
 [9,] 1.905341  1.7157471  1.5695309
[10,] 4.018424 -0.6564554  1.7427306

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352