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

How do I transform list of lists into a dataframe where outerlists are columns and innerlist (of each outerlist) are rows

I have a list of list with thousands of measurements. What I want is to transform the list of list into a dataframe where each outerlist is a column and the values of each innerlist are rows. So that list[[1]][1]] and list[[2]][[1]] are "rbinded" into the same column.

Example list:

set.seed(1)
list <- list(list(round(runif(2), 1), round(runif(2), 1), round(runif(2), 1)),
     list(round(runif(2), 1), round(runif(2), 1), round(runif(2), 1)),
     list(round(runif(2), 1), round(runif(2), 1), round(runif(2), 1)))

What I want is to transform it to the following dataset:

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

df <- data.frame(col1 = c(0.3, 0.4, 0.9, 0.7, 0.7, 0.4),
                col2 = c(0.6, 0.9, 0.6, 0.1, 0.8, 0.5),
                col3 = c(0.2, 0.9, 0.2, 0.2, 0.7, 1))

Is there a way to this automatically? Answers in baseR are very much appreciated.

Thanks for any help.

>Solution :

A possible solution in base R:

do.call("rbind", lapply(list, \(x) setNames(data.frame(x),
  paste0("col", 1:length(x)))))

#>   col1 col2 col3
#> 1  0.3  0.6  0.2
#> 2  0.4  0.9  0.9
#> 3  0.9  0.6  0.2
#> 4  0.7  0.1  0.2
#> 5  0.7  0.8  0.7
#> 6  0.4  0.5  1.0

Another possible solution, using tidyverse:

library(tidyverse)

map_dfr(list, ~ data.frame(.x) %>% set_names(str_c("col", 1:length(.x))))

#>   col1 col2 col3
#> 1  0.3  0.6  0.2
#> 2  0.4  0.9  0.9
#> 3  0.9  0.6  0.2
#> 4  0.7  0.1  0.2
#> 5  0.7  0.8  0.7
#> 6  0.4  0.5  1.0
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