[R] Appending intermediate terms in a For Loop

Douglas Bates bates at stat.wisc.edu
Mon Dec 15 21:05:56 CET 2003


Jason.L.Higbee at stls.frb.org writes:

> I can't figure out how to append intermediate terms inside a For loop.  My 
> use of append(), various indexing, and use of data frames, vectors, 
> matrices has been fruitless.  Here's a simplified example of what I'm 
> talking about:
> 
> i <- 1
> for(i in 10) {
>     v[i] <- i/10
> }
> > v
>  [1]  1 NA NA NA NA NA NA NA NA  1

I think you want

for(i in 1:10)

not

for(i in 10)

> 
> I would like: [1] 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
> 
> Any help on this would be greatly appreciated.
> 
> PS:  I realize that I could have gone v <- 1:10, then v <- v / 10, as I 
> said this is a simplified example; the actual function to be evaluated 
> iteratively in the for loop is more complex than just "x /10"

Generally it is easier to take the "whole object" approach to creating
vectors, as you mention in your P.S.

However, if it really is necessary to iterate over the elements of a
vector a good way of doing it is to establish the vector at the
correct length first, then iterate over it.  The preferred for loop is

> v = numeric(10)
> for (i in seq(along = v)) {
+     v[i] = i/10
+ }
> v
 [1] 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

The reason that seq(along = v) is preferred to 1:length(v) is that the
former gives the correct loop when v has length zero.




More information about the R-help mailing list