[R] Add row to data frame

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Dec 8 15:33:14 CET 2003


On Mon, 8 Dec 2003, Pascal A. Niklaus wrote:

> Martin Maechler wrote:
> 
> >>>>>>"Pascal" == Pascal A Niklaus <Pascal.Niklaus at unibas.ch>
> >>>>>>    on Mon, 08 Dec 2003 11:47:02 +0100 writes:
> >>>>>>            
> >>>>>>
> >
> >    Pascal> Hi all, is there an easy way to build up a data
> >    Pascal> frame by sequentially adding individual rows? 
> >
> >yes, pretty easy, but usually not recommended because quite
> >inefficient.
> >
> >rbind() does work with data frames in the cases we know.
> >Have a look at help(rbind.data.frame)
> >
> >
> >    Pascal> The data frame consists of numeric and character
> >    Pascal> columns. I thought of rbind, but I ended up with
> >    Pascal> numeric values for the character columns.
> >
> >We'd need to see [i.e give a reproducible example!]
> >how you "ended up with numeric values for the  character
> >columns" -- which I guess were *factor* instead of character ?
> >  
> >
> Yes, there was a factor...  There's one problem left, though... The row 
> names are 1, 11, 111 etc, instead of 1,2,3...
> 
>  > df <- NULL;
>  >
>  > df <- rbind(df,data.frame(A=1,B="abc",C=rnorm(1)))
>  > df <- rbind(df,data.frame(A=1,B="abc",C=rnorm(1)))
>  > df <- rbind(df,data.frame(A=1,B="abc",C=rnorm(1)))
>  > df
>     A   B          C
> 1   1 abc  1.3540030
> 11  1 abc -0.7229597
> 111 1 abc -0.4922653
> 
> Of course, I can do a  attr(df,"row.names") <- 1:3 at the end, but is 
> there an easier way? Ideally, I would like to name the row already when 
> adding it to the data frame.

Easy!  Create the data frame with the row names you want -- see 
?data.frame.

> Is there another way than setting the 
> row.names attribute "manually" with the attr command?

What do you think row.names<- does?

-- 
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