Is there an easy way to convert a named list into a dataframe, preserving the elements of the list in a "list-column"?
library(dplyr)
library(magrittr)
## make a random matrix
rand_mat <- function() {
Nrow <- sample(2:15,1)
Ncol <- sample(2:15,1)
rpois(Nrow*Ncol,20) %>%
matrix(nrow = Nrow,ncol = Ncol)
}
## make a named list
unnamed.list <- replicate(10,rand_mat(),simplify = FALSE)
named.list <- unnamed.list %>% set_names(LETTERS[1:10])
list_to_df <- function(listfordf){
if(!is.list(listfordf)) stop("it should be a list")
if(listfordf %>% names %>% is.null) {
seq_along(listfordf) %>%
data.frame(matname = ., stringsAsFactors = FALSE) %>%
rowwise %>%
do(list.element = listfordf %>% extract2(.$matname))
} else {
names(listfordf) %>%
data.frame(matname = ., stringsAsFactors = FALSE) %>%
group_by(matname) %>%
do(comm.matrix = listfordf %>% extract2(.$matname))
}
}
list_to_df(unnamed.list)
## Source: local data frame [10 x 1]
## Groups: <by row>
##
## list.element
## 1 <int[7,11]>
## 2 <int[15,14]>
## 3 <int[6,4]>
## 4 <int[11,14]>
## 5 <int[2,10]>
## 6 <int[11,13]>
## 7 <int[11,11]>
## 8 <int[13,8]>
## 9 <int[11,5]>
## 10 <int[4,15]>
list_to_df(named.list)
## Source: local data frame [10 x 1]
## Groups: <by row>
##
## list.element
## 1 <int[7,11]>
## 2 <int[15,14]>
## 3 <int[6,4]>
## 4 <int[11,14]>
## 5 <int[2,10]>
## 6 <int[11,13]>
## 7 <int[11,11]>
## 8 <int[13,8]>
## 9 <int[11,5]>
## 10 <int[4,15]>
The dplyr package is used to apply the "Split-Apply-Combine" method of
data analysis. Many useRs might have previously used named lists in
combination with plyr::llply
or plyr::ldply
, applying a function to
each section before combining them.
Now in my misc package, with slight modifications: https://github.com/krlmlr/kimisc/blob/develop/R/list_to_df.R