[R] Store results of for loop
Thomas Lumley
tlumley at u.washington.edu
Mon Apr 24 22:45:13 CEST 2006
On Mon, 24 Apr 2006, 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
> }
>
> 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
> }
>
> What I am hoping for is that results should be a vector of length 3.
>
either
results<-sapply(ss, function(i) i+1)
or
for(i in seq(along=ss)){
results[i]<-ss[i]+1
}
-thomas
Thomas Lumley Assoc. Professor, Biostatistics
tlumley at u.washington.edu University of Washington, Seattle
More information about the R-help
mailing list