Search code examples
rmultiple-columns

Split a list column into multiple columns


I have a data frame where the last column is a column of lists. Below is how it looks:

Col1 | Col2 | ListCol
--------------------------
 na  |  na  | [obj1, obj2]
 na  |  na  | [obj1, obj2]
 na  |  na  | [obj1, obj2]

What I want is

Col1 | Col2 | Col3  | Col4
--------------------------
 na  |  na  | obj1  | obj2
 na  |  na  | obj1  | obj2
 na  |  na  | obj1  | obj2

I know that all the lists have the same amount of elements.

Edit:

Every element in ListCol is a list with two elements.


Solution

  • Here is one approach, using unnest and tidyr::spread...

    library(dplyr)
    library(tidyr)
    
    #example df
    df <- tibble(a=c(1, 2, 3), b=list(c(2, 3), c(4, 5), c(6, 7)))
    
    df %>% unnest(b) %>% 
           group_by(a) %>% 
           mutate(col=seq_along(a)) %>% #add a column indicator
           spread(key=col, value=b)
    
          a   `1`   `2`
      <dbl> <dbl> <dbl>
    1    1.    2.    3.
    2    2.    4.    5.
    3    3.    6.    7.