[R] Converting a list to a data frame

Kevin E. Thorpe kevin@thorpe @ending from utoronto@c@
Thu May 3 20:20:13 CEST 2018


On 05/03/2018 01:28 PM, Hadley Wickham wrote:
> On Wed, May 2, 2018 at 11:53 AM, Jeff Newmiller
> <jdnewmil at dcn.davis.ca.us> wrote:
>> Another approach:
>>
>> ########
>> library(tidyr)
>> L <- list( A = data.frame( x=1:2, y=3:4 )
>>           , B = data.frame( x=5:6, y=7:8 )
>>           )
>> D <- data.frame( Type = names( L )
>>                 , stringsAsFactors = FALSE
>>                 )
>> D$data <- L
>> unnest(D, data)
>> #>   Type x y
>> #> 1    A 1 3
>> #> 2    A 2 4
>> #> 3    B 5 7
>> #> 4    B 6 8
>> ########
> 
> I think a slightly more idiomatic tidyverse solution is dplyr::bind_rows()
> 
> l <- list(
>    A = data.frame(x = 1:2, y = 3:4),
>    B = data.frame(x = 5:6, y = 7:8)
> )
> 
> dplyr::bind_rows(l, .id = "type")
> #>   type x y
> #> 1    A 1 3
> #> 2    A 2 4
> #> 3    B 5 7
> #> 4    B 6 8
> 
> This also has the advantage of returning a data frame when the inputs
> are data frames.
> 
> Hadley
> 

I _clearly_ need to learn the dplyr package.

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