Jason.L.Higbee@stls.frb.org
2003-Dec-15 19:47 UTC
[R] Appending intermediate terms in a For Loop
R UseRs: 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 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. -Jason 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" [[alternative HTML version deleted]]
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 1I 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.