[R] Q: appending to non-existent vector?

Duncan Murdoch murdoch at stats.uwo.ca
Fri Sep 21 19:47:47 CEST 2007

On 9/21/2007 1:15 PM, D. R. Evans wrote:
> This is a real newbie question. What makes it worse is that I know
> I've seen the answer somewhere, but I can no longer find it.
> If I have a loop that is supposed to generate a vector piecemeal,
> adding an element each time through the loop, what do I do to stop it
> failing the first time around the loop, when the vector doesn't yet
> exist (so I can't use the append() function)?

You can create an empty vector to start.  Exactly how depends on what 
you're putting in it, but something like numeric(0) or list() should do 
what you want.

Of course, this is a very slow way to build results:  your code will run 
much faster if you allocate all the space you need at the beginning, and 
just fill in the values as you go, e.g.

x <- numeric(100)
i <- 0
while (more stuff) {
  i <- i+1
  x[i] <- stuff

Duncan Murdoch

More information about the R-help mailing list