0

Given a list of n elements with different lengths as below:

library(tidyverse)
l <- list(
  "a" = c(1,2),
  "b" = c(3),
  "c" = c(4,5,6)
)

I would like to convert this list to the following data frame:

out <- data.frame(
  foo = c("a", "a", "b","c","c","c"),
  bar = c(1:6)
)

print(out)
#>   foo bar
#> 1   a   1
#> 2   a   2
#> 3   b   3
#> 4   c   4
#> 5   c   5
#> 6   c   6

What is the best and easiest way to achieve this in R? I managed to get the desired output, but the code seems cumbersome and too complicated:

df <- data.frame()

for (i in 1:length(l)){
  d <- data.frame(
    names(l[i]) <-  l[i]
  )
  d <- d %>% pivot_longer(1,names_to = "foo", values_to = "bar")
  df <- bind_rows(df,d)
}

print(df)
#>   foo bar
#> 1   a   1
#> 2   a   2
#> 3   b   3
#> 4   c   4
#> 5   c   5
#> 6   c   6

Created on 2021-10-05 by the reprex package (v2.0.0)

MKR
  • 1,620
  • 7
  • 20

1 Answers1

1
library(tidyverse)

l <- list(
  "a" = c(1,2),
  "b" = c(3),
  "c" = c(4,5,6)
)
l
#> $a
#> [1] 1 2
#> 
#> $b
#> [1] 3
#> 
#> $c
#> [1] 4 5 6

l %>% enframe() %>% unnest(value)
#> # A tibble: 6 x 2
#>   name  value
#>   <chr> <dbl>
#> 1 a         1
#> 2 a         2
#> 3 b         3
#> 4 c         4
#> 5 c         5
#> 6 c         6

Created on 2021-10-05 by the reprex package (v2.0.1)

danlooo
  • 10,067
  • 2
  • 8
  • 22