[R] How to fix indeces in a loop

Sarah Goslee sarah.goslee at gmail.com
Fri May 18 17:19:15 CEST 2012


Hi Francesca,

Here's one approach:

loopvalues <- c(100,1000,10000)
results <- numeric(length(loopvalues))

for(loopindex in 1:length(loopvalues)) {
	i <- loopvalues[loopindex]
	results[loopindex] <- mean(i)
        # assuming your intent is actually something other
        # than taking the mean of a single number
}

You could also use c() inside the loop, but that is much less
efficient, especially if your loop is large.

Note though that results is not a "vector of dimension 3," which is
meaningless, but a vector of length 3.

Sarah

On Fri, May 18, 2012 at 10:59 AM, Francesca
<francesca.pancotto at gmail.com> wrote:
> 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
>

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list