[R] Converting a list to a data frame

Eivind K. Dovik he||o @end|ng |rom e|v|nddov|k@com
Wed May 2 19:38:35 CEST 2018


On Wed, 2 May 2018, Kevin E. Thorpe 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

Hi, Kevin.

Here's code that will generate your desired data frame.

# List as provided
thelist <- list(A=data.frame(x=1:2, y=3:4),B=data.frame(x=5:6,y=7:8))
thelist

# Creating the type-vector
type <- c()
for(i in 1:length(thelist)){
   type <- c(type, rep(names(thelist)[i], sapply(thelist, nrow)[i]))
}

# Creating the data frame
df <- data.frame(type, do.call(rbind.data.frame, c(thelist, make.row.names 
= FALSE)))
df


Kind regards,
Eivind K. Dovik
Bergen, NO




>
> -- 
> 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/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list