I have a data frame (tibble) with multiple nested columns nested in a single list, like this example
nested= mtcars%>%
nest(extra = c("drat", "wt" , "qsec" ,"vs", "am", "gear" ,"carb"))
How do I unnest a single column from this list, without unnesting all and renesting the ones I still nested.
For example, with this data, can I just unnest gsec
?
You can use map()
to grab out that column and then unnest that.
nested %>%
mutate(qsec = map(extra, "qsec")) %>%
unnest_longer(qsec)
Notice though that this might create problems depending on what you do. This is because you'll now potentially have duplicates with the rest of the nested data. Might be safer to just unnest and nest again.
# A tibble: 32 x 6
mpg cyl disp hp extra qsec
<dbl> <dbl> <dbl> <dbl> <list> <dbl>
1 21 6 160 110 <tibble [2 x 7]> 16.5
2 21 6 160 110 <tibble [2 x 7]> 17.0
3 22.8 4 108 93 <tibble [1 x 7]> 18.6
4 21.4 6 258 110 <tibble [1 x 7]> 19.4
5 18.7 8 360 175 <tibble [1 x 7]> 17.0
6 18.1 6 225 105 <tibble [1 x 7]> 20.2
7 14.3 8 360 245 <tibble [1 x 7]> 15.8
8 24.4 4 147. 62 <tibble [1 x 7]> 20
9 22.8 4 141. 95 <tibble [1 x 7]> 22.9
10 19.2 6 168. 123 <tibble [1 x 7]> 18.3