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)