[R] Converting a list to a data frame

Kevin E. Thorpe kevin.thorpe at utoronto.ca
Fri Nov 4 13:37:59 CET 2016


There is probably a very simple elegant way to do this, but I have been 
unable to find it. Here is a toy example. Suppose I have a list of data 
frames like this.

  print(x <- 
list('1'=data.frame(id=1:4,expand.grid(x1=0:1,x2=0:1)),'2'=data.frame(id=5:8,expand.grid(x1=2:3,x2=2:3))))
$`1`
   id x1 x2
1  1  0  0
2  2  1  0
3  3  0  1
4  4  1  1

$`2`
   id x1 x2
1  5  2  2
2  6  3  2
3  7  2  3
4  8  3  3

The real application will have more than 2 elements so I'm looking for a 
general approach. I basically want to rbind the data frames in each list 
element and add a variable that adds the element name. In this example 
the result would look something like this.

rbind(data.frame(set='1',x[[1]]),data.frame(set='2',x[[2]]))
   set id x1 x2
1   1  1  0  0
2   1  2  1  0
3   1  3  0  1
4   1  4  1  1
5   2  5  2  2
6   2  6  3  2
7   2  7  2  3
8   2  8  3  3

Obviously, for 2 elements the simple rbind works but I would like a 
general solution for arbitrary length lists. Hopefully that is clear.

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 at utoronto.ca  Tel: 416.864.5776  Fax: 416.864.3016



More information about the R-help mailing list