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

Greg Snow Greg.Snow at intermountainmail.org
Fri Sep 21 19:43:44 CEST 2007


Something like this:

myvec <- NULL

while( condition ) {
  myvec <- c(myvec, additional stuff)
}

However, if you know ahead of time how long the vector will be (you are
adding 1 element at a time), then it is best to initialize the vector to
the correct length:

myvec <- numeric(1000)

for (i in 1:1000) {
	myvec[i] <- additional stuff
}

In the second case you create a vector of length 1000 then insert
numbers into it.  In the first case you first create a vector of length
1, then next time through you create a new vector of length 2, copy a
value into position 1 then insert the new value into position 2 then
give it the same name as the previous vector (allowing the previous
version to be garbage collected at some point), on the 3rd iteration you
create a new vector of length 3, copy 2 values and insert 1, etc.  You
can see that that can fragment memory and take unneeded time which is
why the second method is prefered.  The only time to use the first
method is if you don't know how long each piece of 'additional stuff' is
and you know that you will only be doing the loop a few times.


Hope this helps,


-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at intermountainmail.org
(801) 408-8111
 
 

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of D. R. Evans
> Sent: Friday, September 21, 2007 11:15 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Q: appending to non-existent vector?
> 
> 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)?
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 



More information about the R-help mailing list