Skip to content

Instantly share code, notes, and snippets.

@rdinnager
Forked from aammd/ListToDf.md
Created June 6, 2014 05:59
Show Gist options
  • Save rdinnager/a8cc8d26a4a0790c1c0a to your computer and use it in GitHub Desktop.
Save rdinnager/a8cc8d26a4a0790c1c0a to your computer and use it in GitHub Desktop.

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
named.list <- replicate(10,rand_mat(),simplify = FALSE) %>%
  set_names(LETTERS[1:10])

names(named.list) %>%
  data.frame(matname = ., stringsAsFactors = FALSE) %>%
  group_by(matname) %>%
  do(comm.matrix = named.list %>% extract2(.$matname))

## Source: local data frame [10 x 2]
## Groups: <by row>
## 
##    matname  comm.matrix
## 1        A   <int[5,4]>
## 2        B  <int[4,13]>
## 3        C   <int[5,5]>
## 4        D  <int[9,13]>
## 5        E  <int[2,13]>
## 6        F  <int[15,3]>
## 7        G   <int[2,5]>
## 8        H  <int[6,14]>
## 9        I <int[14,15]>
## 10       J <int[13,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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment