Rasyid Ridha Rasyid Ridha - 1 year ago 65
R Question

Unnest one column list to many columns in tidyr

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

Answer Source

With dplyr and purrr

df %>% 
  mutate(ctn = map(ctn, as_tibble)) %>%
  unnest()
# A tibble: 2 x 3
     id     a     b
  <int> <chr> <dbl>
1     1     x     1
2     2     y     2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download