[R] Converting a list to a data frame

William Dunlap wdunl@p @ending from tibco@com
Thu May 3 23:31:41 CEST 2018


If you require that the 'type' column be a factor with a level for each
element of the input list, then you need to do that after calling
dplyr::bind_rows(), just as with the base-R solutions.

> l <- list( A = data.frame(X=1:2, Y=11:12), B = data.frame(X=integer(),
Y=integer()), C = data.frame(X=3L, Y=13L) )
> str(d <- dplyr::bind_rows(l, .id = "Which") )
'data.frame':   3 obs. of  3 variables:
 $ Which: chr  "A" "A" "C"
 $ X    : int  1 2 3
 $ Y    : int  11 12 13
> d$Which <- factor(d$Which, levels=names(l))
> str(d)
'data.frame':   3 obs. of  3 variables:
 $ Which: Factor w/ 3 levels "A","B","C": 1 1 3
 $ X    : int  1 2 3
 $ Y    : int  11 12 13

Sometimes you need the names of the of the 0-row data.frames in the output
to make plots, etc., comparable across various samples of the data.


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Thu, May 3, 2018 at 10:28 AM, Hadley Wickham <h.wickham at gmail.com> 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
>
> --
> http://hadley.nz
>
> ______________________________________________
> R-help at 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.
>

	[[alternative HTML version deleted]]




More information about the R-help mailing list