2

I have a with numerical elements of different length of the form

list1 <- 1 : 2
list2 <- 1 : 3
list3 <- c(10, 100)


mylist <- list(a = list1, b = list2, c = list3)

and I would like to transform it into a data frame like this one

# a 1
# a 2
# b 1
# b 2
# b 3
# c 10
# c 100

Is there a way to do it?

Logos
  • 151
  • 7
  • 1
    `stack(mylist)` – Onyambu Feb 17 '23 at 21:32
  • 1
    @akrun, I noticed that there was an error in the previous one. But thank you so much for both solutions: `expand.grid` is going to be useful. Thank you for the updated solution too. – Logos Feb 17 '23 at 23:43
  • Duplicate: [Named List To/From Data.Frame](https://stackoverflow.com/questions/10432993/named-list-to-from-data-frame) – Henrik Feb 18 '23 at 18:27

2 Answers2

2

We could directly apply expand.grid on a list

expand.grid(mylist)

Or with expand_grid from tidyr

library(tidyr)
expand_grid(!!!mylist)

For the updated dataset

library(tibble)
enframe(mylist) %>% 
  unnest(value)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

An alternative to e.g. expand.grid using lapply

data.frame(do.call(rbind, lapply(mylist$b, function(x) cbind(x, y = mylist$a))))
   x y
1  1 1
2  1 2
3  1 3
4  1 4
5  1 5
6  2 1
7  2 2
8  2 3
9  2 4
10 2 5
11 3 1
12 3 2
13 3 3
14 3 4
15 3 5
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29