Skip to content

double for cycle

3 messages · cesare orsini, David L Carlson

#
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
+ s[n]=1+s[n]+rnorm(1,mean=0,sd=1)
+ }
[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.
#
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
#
thank you Mr. Carlson

you're right, the matrix that I used as an example does not make sense.
When I built the array I was not thinking of the formula
s[n]=1+s[n]+rnorm(1,mean=0,sd=1), I just wanted to give an example of the
structure of the matrix that I needed.

Anyway I think you have solved my simple problem.

thank you for availability !!

Cesare

--
View this message in context: http://r.789695.n4.nabble.com/double-for-cycle-tp4636916p4636988.html
Sent from the R help mailing list archive at Nabble.com.