Search code examples
rdatatable

Convert 3 level nested list with vectors into dataframe


My source data looks like this:

data <- list(row1 = list(D = data.table(stat = "D", est = 0.2), HM = data.table(stat = c("H","M"), est = c(0.4,0.5))),
             row2 = list(D = data.table(stat = "D", est = 0.3), HM = data.table(stat = c("H","M"), est = c(0.1,0.6))))

I want it to look like this:

enter image description here

I apply some solutions in this post, for de-nesting lists, for example:

as.data.frame(t(sapply(data, unlist)))

But I get:

enter image description here

Seems like I could do one more step and try to manually clean the latter, but the actual data is more populous and with more variables. I thought I needed to first reconvert doubles (vectors) into singles but after that result is the same. Any ideas?


Solution

  • Here is a clunky solution using dplyr::bind_rows().

    Use lapply() to bind the sublists together and then row_bind the parent lists together.

    library(dplyr)
    bind_rows(lapply(data, bind_rows))
    
      stat est
    1    D 0.2
    2    H 0.4
    3    M 0.5
    4    D 0.3
    5    H 0.1
    6    M 0.6
    

    This will work for list which are 2 level deep, if it is 3 levels deep, then another lapply() is needed.