[R] Convert a "by" list into a data frame

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Jun 27 11:17:03 CEST 2005


Gabor Grothendieck <ggrothendieck at gmail.com> writes:

> On 6/26/05, Tudor Bodea <gtg757i at mail.gatech.edu> wrote:
> > Dear useRs,
> > 
> > Is there a way to convert a list generated by "by" command into a data frame?
> 
> Here is an example which creates a by object whose elements
> are the first row of each Species of iris.  The next line converts
> that to a data frame:
> 
>    by.object <- by(iris, iris$Species, head, 1)
>    do.call("rbind", by.object)

Also, check if aggregate() does the trick:

>  aggregate(iris, list(iris$Species), head, 1)
     Group.1 Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1     setosa          5.1         3.5          1.4         0.2       1
2 versicolor          7.0         3.2          4.7         1.4       2
3  virginica          6.3         3.3          6.0         2.5       3


>    by.object <- by(iris, iris$Species, head, 1)
>    do.call("rbind", by.object)
           Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
setosa              5.1         3.5          1.4         0.2     setosa
versicolor          7.0         3.2          4.7         1.4 versicolor
virginica           6.3         3.3          6.0         2.5  virginica

But notice the differences...

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907




More information about the R-help mailing list