1

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?

luchonacho
  • 6,759
  • 4
  • 35
  • 52

2 Answers2

3

Seems you just need to flatten the list and row bind:

library(data.table) # your example data contains data tables
do.call(rbind, unlist(data, recursive = FALSE))
   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

Or with data.table::rbindlist()

rbindlist(unlist(data, recursive = FALSE))
Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56
2

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.

Dave2e
  • 22,192
  • 18
  • 42
  • 50