[R] Q: appending to non-existent vector?
hadley wickham
h.wickham at gmail.com
Fri Sep 21 20:19:39 CEST 2007
On 9/21/07, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
> 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
> }
Or if you wanted to be really fancy:
while (more stuff) {
i <- i+1
if (i > length(x)) length(x) <- 2 * length(x)
x[i] <- stuff
}
which should be O(log n).
Hadley
More information about the R-help
mailing list