[R] How to fix indeces in a loop

arun smartpink111 at yahoo.com
Fri May 18 18:21:43 CEST 2012


Hi Francesca,

> for(i in 1:length(x1<-c(100,1000,10000))){
 j<-x1[i]
 x1[i]<-mean(j)
 }

> x1
[1]   100  1000 10000



A.K.



----- Original Message -----
From: Francesca <francesca.pancotto at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Friday, May 18, 2012 10:59 AM
Subject: [R] How to fix indeces in a loop

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

______________________________________________
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.




More information about the R-help mailing list