[R] How to fix indeces in a loop

Francesca francesca.pancotto at gmail.com
Fri May 18 16:59:38 CEST 2012


Dear Contributors,
I have an easy question for you which is puzzling me instead.
I am running loops similar to the following:


for (i in c(100,1000,10000)){

print((mean(i)))
#var<-var(rnorm(i,0,1))
}

This is what I obtain:

[1] 100
[1] 1000
[1] 10000

In this case I ask the software to print out the result, but I would
like to store it in an object.
I have tried a second loop, because if I index the out put variable
with the i , i get thousands of records which I do not want(a matrix
of dimension 10000).

for (i in c(100,1000,10000)){
for (j in 1:3){
x[j]<-((mean(i)))
#var<-var(rnorm(i,0,1))
}}

This is the x:

      [,1] [,2] [,3]
[1,] 10000   NA   NA
[2,] 10000   NA   NA
[3,] 10000   NA   NA

Clearly the object x is storing only the last value of i, 10000.

I would like to save a vector of dimension 3 with content 100,1000,10000,
but I do not know how to fix the index in an efficient manner.

Thanks for any help you can provide.
Francesca



More information about the R-help mailing list