Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading