Unnest one column list to many columns in tidyr

Viewed 2239

For example, I have a tidy data frame like this:

df <- tibble(id=1:2,
         ctn=list(list(a="x",b=1),
                  list(a="y",b=2)))
# A tibble: 2 x 2
     id        ctn
  <int>     <list>
1     1 <list [2]>
2     2 <list [2]>

How could I unnest ctn column to the right so that the data frame will be like this:

# A tibble: 2 x 3
     id     a     b
  <int> <chr> <dbl>
1     1     x     1
2     2     y     2
3 Answers

In a tidy way we can now (dplyr 1.0.2 and above) do this using rowwise():

df %>% rowwise() %>% mutate(as_tibble(ctn))
# A tibble: 2 x 4
# Rowwise: 
     id ctn              a         b
  <int> <list>           <chr> <dbl>
1     1 <named list [2]> x         1
2     2 <named list [2]> y         2

And sticking to purrr we can also:

df %>% mutate(map_dfr(ctn, as_tibble))
# A tibble: 2 x 4
     id ctn              a         b
  <int> <list>           <chr> <dbl>
1     1 <named list [2]> x         1
2     2 <named list [2]> y         2
Related