[R] rbind and data.frame
Göran Broström
gb at stat.umu.se
Wed Dec 5 12:05:41 CET 2001
On 5 Dec 2001, Peter Dalgaard BSA wrote:
> Göran Broström <gb at stat.umu.se> writes:
>
> > Version 1.3.1 (2001-08-31) (RH 7.2):
> >
> > > dat <- data.frame(x = 1, y = 2)
> > > x <- matrix(0, ncol = 2, nrow = 2)
> > > x
> > [,1] [,2]
> > [1,] 0 0
> > [2,] 0 0
> > > dat
> > x y
> > 1 1 2
> > > rbind(dat, x)
> > x y
> > 1 1 2
> > 2 0 0
> >
> > I expected
> >
> > > rbind(dat, x)
> > x y
> > 1 1 2
> > 2 0 0
> > 3 0 0
> >
> > Is my expectation wrong?
>
> Maybe and maybe not... The help page has
>
> If you want to combine other objects with data frames, it may be
> necessary to coerce them to data frames first.
>
> and the internal logic in rbind.data.frame is that everything that is
> not a data frame or a list is a vector. I'm slightly puzzled as to why
> we don't check the lengths but quietly truncate or recycle (whereas
> the corresponding cbind code does protest even though we don't always
> want it to...)
The help page also have:
The functions `cbind' and `rbind' are generic, with methods for
data frames. The data frame method will be used if an argument is
a data frame and the rest are vectors or matrices.
^^^^^^^^^^^
Maybe somewhat misleading? However, this is the way to do it:
> dat <- data.frame(x = 1, y = 2)
> x <- matrix(NA, ncol = 2, nrow = 2)
> x <- data.frame(x) ## Why no 'names =' arg?
> names(x) <- names(dat) ## Necessary
> rbind(dat, x)
x y
1 1 2
2 NA NA
3 NA NA
My real problem is how to create a data frame in a sequentially growing
manner, when I know the final size (no of cases). I want to avoid to
call 'rbind' many times, and instead create an 'empty' data frame in
one call, and then fill it. Are there better ways of doing this?
Göran
--
Göran Broström tel: +46 90 786 5223
professor fax: +46 90 786 6614
Department of Statistics http://www.stat.umu.se/egna/gb/
Umeå University
SE-90187 Umeå, Sweden e-mail: gb at stat.umu.se
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list