Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn a list with elements of unequal length into a two column dataframe

I have a list with 3 elements, each with a different set, and number, of values. I would like to turn this list into a simple two column dataframe.

One column would be the value from the list element, the second column would be the name of the list element itself.

myList <- list(A = c(1,2,3),
               B = c(10,20,30,40),
               C = c(100,200,300,400,500))

So the ideal outcome is something like:

Value     List
1         A
2         A
10        B
100       C
......

So I know I can do this with a series of rbinds:

df <-   data.frame(Value = myList[[A]],cluster = A) %>%
  rbind(data.frame(Value = myList[[B]],cluster = B)) %>%
  rbind(data.frame(Value = myList[[C]],cluster = C))

And I can probably clean this up with a loop or lapply...but it seems like there should be a more straightforward way to get this!

like image 715
Max F Avatar asked Sep 11 '25 01:09

Max F


1 Answers

We can use stack from base R

stack(myList)

-output

   values ind
1       1   A
2       2   A
3       3   A
4      10   B
5      20   B
6      30   B
7      40   B
8     100   C
9     200   C
10    300   C
11    400   C
12    500   C
like image 151
akrun Avatar answered Sep 14 '25 00:09

akrun