[R] How to append to a data.frame?

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Dec 9 07:34:07 CET 2003


On Tue, 9 Dec 2003, David Kreil wrote:

> 
> Hi,
> 
> I have a data.frame that I need to construct iteratively.
> 
> At the moment, I'm doing:
> 
> d<-data.frame(x=c(),y=c(),z=());
> 
> # {and, within some loop}
> 
>   d<-rbind(d,data.frame(x=newx,y=newy,z=newz);
> 
> 
> While this works, it is horribly verbose and probably not efficient, either. 
> My real data.frame has, of course, many more columns, which can be of 
> different modes.
> 
> I vaguely recall that in much earlier R versions the following worked
> 
>   d[dim(d)[1]+1,]<-c(newx,newy,newz);
> 
> but not anymore (both 1.7 and 1.8 give "subscript out of bounds").
> 
> Can anyone suggest a more elegant and/or efficient way of achieving this, 
> please? Cc to this address highly appreciated.

Just allocate a large enough data frame to start with, then use indexing
to insert the rows.  If you cannot get a good bound on the eventual size,
over-allocate and double in size as needed.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list