[R] Converting a list to a data frame

William Dunlap wdun|@p @end|ng |rom t|bco@com
Wed May 2 19:28:11 CEST 2018


> x1 <- do.call(rbind, c(x, list(make.row.names=FALSE)))
> x2 <- cbind(type=rep(names(x), vapply(x, nrow, 0)), x1)
> str(x2)
'data.frame':   4 obs. of  3 variables:
 $ type: Factor w/ 2 levels "A","B": 1 1 2 2
 $ x   : int  1 2 5 6
 $ y   : int  3 4 7 8


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Wed, May 2, 2018 at 10:11 AM, Kevin E. Thorpe <kevin.thorpe using utoronto.ca>
wrote:

> I suspect this is pretty easy, but I'm having trouble figuring it out.
> Basically, I have a list of data frames such as the following example:
>
> list(A=data.frame(x=1:2, y=3:4),B=data.frame(x=5:6,y=7:8))
>
> I would like to turn this into  data frame where the list elements are
> essentially rbind'ed together and the element name becomes a new variable.
> For example, I would like to turn the list above into a data frame that
> looks like this:
>
> data.frame(type=c("A","A","B","B"),x=c(1:2,5:6),y=c(3:4,7:8))
>
> Appreciate any pointers.
>
> Kevin
>
> --
> Kevin E. Thorpe
> Head of Biostatistics,  Applied Health Research Centre (AHRC)
> Li Ka Shing Knowledge Institute of St. Michael's Hospital
> Assistant Professor, Dalla Lana School of Public Health
> University of Toronto
> email: kevin.thorpe using utoronto.ca  Tel: 416.864.5776  Fax: 416.864.3016
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posti
> ng-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]




More information about the R-help mailing list