Converting list object to a data frame object is common in R. There are many ways and here is another way using tidyverse packages.
bind_cols()
This is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one (cited from tidyverse package site).
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.1.0 ✔ purrr 0.2.5
## ✔ tibble 1.4.2 ✔ dplyr 0.7.7
## ✔ tidyr 0.8.2 ✔ stringr 1.3.1
## ✔ readr 1.1.1 ✔ forcats 0.3.0
## ── Conflicts ────────────────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
one <- mtcars[,1:4]
two <- mtcars[,c(1:10)]
# Showing how dplyr::select in sapply works
sapply(list(ONE=one,TWO=two), dplyr::select,mpg)
## $ONE.mpg
## [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2
## [15] 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4
## [29] 15.8 19.7 15.0 21.4
##
## $TWO.mpg
## [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2
## [15] 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4
## [29] 15.8 19.7 15.0 21.4
# Convert into data.frame by bind_cols(). Bind_cols() can be used with list object.
sapply(list(ONE=one,TWO=two), dplyr::select,mpg) %>% bind_cols()
## # A tibble: 32 x 2
## ONE.mpg TWO.mpg
## <dbl> <dbl>
## 1 21 21
## 2 21 21
## 3 22.8 22.8
## 4 21.4 21.4
## 5 18.7 18.7
## 6 18.1 18.1
## 7 14.3 14.3
## 8 24.4 24.4
## 9 22.8 22.8
## 10 19.2 19.2
## # ... with 22 more rows
# does not work why?
sapply(list(ONE=one,TWO=two), dplyr::select,mpg) %>% bind_cols(one[,1],.)
## Error in cbind_all(x): Argument 1 must have names
one[,1]
## [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2
## [15] 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4
## [29] 15.8 19.7 15.0 21.4
# Does work
sapply(list(ONE=one,TWO=two), dplyr::select,mpg) %>% bind_cols(list(model=rownames(mtcars)),.)
## # A tibble: 32 x 3
## model ONE.mpg TWO.mpg
## <chr> <dbl> <dbl>
## 1 Mazda RX4 21 21
## 2 Mazda RX4 Wag 21 21
## 3 Datsun 710 22.8 22.8
## 4 Hornet 4 Drive 21.4 21.4
## 5 Hornet Sportabout 18.7 18.7
## 6 Valiant 18.1 18.1
## 7 Duster 360 14.3 14.3
## 8 Merc 240D 24.4 24.4
## 9 Merc 230 22.8 22.8
## 10 Merc 280 19.2 19.2
## # ... with 22 more rows
enframe()
Another useful function is enframe1.
x <- list( a = 1: 5, b = 3: 4, c = 5: 6 )
x
## $a
## [1] 1 2 3 4 5
##
## $b
## [1] 3 4
##
## $c
## [1] 5 6
df <- tibble::enframe( x)
df
## # A tibble: 3 x 2
## name value
## <chr> <list>
## 1 a <int [5]>
## 2 b <int [2]>
## 3 c <int [2]>
- Wickham, Hadley; Grolemund, Garrett. R for Data Science: Import, Tidy, Transform, Visualize, and Model Data (p. 414). O’Reilly Media.