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 list of named vectors of different length to tibble

I have the following list

example <- list(a = c(1, 2, 3),
                b = c(2, 3),
                c = c(3, 4, 5, 6))

that I’d like to transform into the following tibble

# A tibble: 9 Ă— 2
  name  value
  <chr> <dbl>
1 a         1
2 a         2
3 a         3
4 b         2
5 b         3
6 c         3
7 c         4
8 c         5
9 c         6

I’ve found multiple StackOverflow questions on this subject like here, here or here, but none is adressing this particular case where the name of the vector is not expected to become a column name.

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 managed to achieve the desired result with a good old loop like below, but I’m looking for a faster and more elegant way.

library(dplyr)

example_list <- list(a = c(1, 2, 3),
                     b = c(2, 3),
                     c = c(3, 4, 5, 6))

example_tibble <- tibble()

for (i in 1:length(example_list)) {
  example_tibble <- example_tibble %>% 
    bind_rows(as_tibble(example_list[[i]]) %>% 
                mutate(name = names(example_list)[[i]]))
}

example_tibble <- example_tibble %>% 
  relocate(name)

>Solution :

Try stack

> stack(example)
  values ind
1      1   a
2      2   a
3      3   a
4      2   b
5      3   b
6      3   c
7      4   c
8      5   c
9      6   c
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