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
> s <- rep(1,10)
> set.seed(42)
> for (n in 2:10) {s[n]=1+s[n]+rnorm(1,mean=0,sd=1)}
> s
[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
> s <- rep(1,10)
> set.seed(42)
> s <- c(s[1], 1 + s[-1] + rnorm(9))
> s
[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
> s <- rep(1,10)
> set.seed(42)
> replicate( 3, c(s[1], 1 + s[-1] + rnorm(9)))
[,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
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of cesare orsini
> Sent: Wednesday, July 18, 2012 12:39 PM
> To: r-help at r-project.org
> Subject: [R] double for cycle
>
> Hi nice people,
>
> i am trying to made a double "for" cycle, i wish that for cycle
on k
> activates t times the for cycle on s
>
> the first cycle is this:
>
> s<-rep(1,10)
> s
> [1] 1 1 1 1 1 1 1 1 1 1
>
> > for (n in 2:10) {
> + s[n]=1+s[n]+rnorm(1,mean=0,sd=1)
> + }
> > s
> [1] 1 4.75 4.86 4.05 4.09 4.56 4.63 4.65 4.12 4.01
>
> now i wish another cycle that activates t times the before cycle gives
> me a
> matrix with t columns and 10 rows
>
> like for example if t=3
>
> 1 1 1
> 4.75 4.56 4.13
> 4.86 4.12 4.58
> 4.05 4.17 4.78
> 4.09 4.44 4.15
> 4.56 4.80 4.15
> 4.63 4.56 4.11
> 4.65 4.22 4.25
> 4.12 4.55 4.56
> 4.01 4.25 4.36
>
> how can i do?
> thank you for avalaibility!
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/double-for-
> cycle-tp4636916.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.