[R] Store results of for loop

Marc Schwartz (via MN) mschwartz at mn.rr.com
Mon Apr 24 22:51:45 CEST 2006


On Mon, 2006-04-24 at 16:31 -0400, Doran, Harold wrote:
> I have what I'm sure will turn out to be straightforward. I want to
> store the results of a loop for some operations from a patterned vector.
> For example, the following doesn't give what I would hope for
> 
> ss <- c(2,3,9)
> results <- numeric(length(ss))
> for (i in seq(along=ss)){
>    results[i] <- i + 1
>    }

Harold,

Here you are getting:

> results
[1] 2 3 4

because 'i' is 1:3, thus:

> 1:3 + 1
[1] 2 3 4


> The following does give what I expect, but creates a vector of length 9.
> 
> ss <- c(2,3,9)
> results <- numeric(length(ss))
> for (i in ss){
>    results[i] <- i + 1
>    }

Here you are getting:

> results
[1]  0  3  4 NA NA NA NA NA 10

because 'i' is set to 'ss' which is c(2, 3, 9). Thus, 'results' is being
indexed as results[c(2, 3, 9)]. 

You are adding 1 to 'ss' in the loop, thus:

> ss + 1
[1]  3  4 10

In short:

  results[ss] <- ss + 1

which yields:

> results
[1]  0  3  4 NA NA NA NA NA 10


> What I am hoping for is that results should be a vector of length 3.

I suspect what you want is:

 ss <- c(2, 3, 9)
 results <- numeric(length(ss))

 for (i in seq(along = ss))
 {
   results[i] <- ss[i] + 1
 }

> results
[1]  3  4 10


You might also want to look at ?sapply, where you could do something
like this:

> sapply(ss, function(x) x + 1)
[1]  3  4 10


HTH,

Marc Schwartz




More information about the R-help mailing list