Mark Davies
Mark Davies

Reputation: 940

How to unnest a single column from a nested list without unnesting all

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?

Upvotes: 1

Views: 1302

Answers (2)

user10917479
user10917479

Reputation:

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

Upvotes: 2

DaveArmstrong
DaveArmstrong

Reputation: 22044

Here's one attempt, though not sure it does exactly what you want:

library(tidyverse)
nested= mtcars%>%
  nest(extra = c("drat", "wt" ,  "qsec" ,"vs",   "am",   "gear" ,"carb"))

nested %>% rowwise() %>% mutate(tmp = list(select(extra, qsec))) %>% unnest(tmp)
#> # A tibble: 32 × 6
#>      mpg   cyl  disp    hp extra             qsec
#>    <dbl> <dbl> <dbl> <dbl> <list>           <dbl>
#>  1  21       6  160    110 <tibble [2 × 7]>  16.5
#>  2  21       6  160    110 <tibble [2 × 7]>  17.0
#>  3  22.8     4  108     93 <tibble [1 × 7]>  18.6
#>  4  21.4     6  258    110 <tibble [1 × 7]>  19.4
#>  5  18.7     8  360    175 <tibble [1 × 7]>  17.0
#>  6  18.1     6  225    105 <tibble [1 × 7]>  20.2
#>  7  14.3     8  360    245 <tibble [1 × 7]>  15.8
#>  8  24.4     4  147.    62 <tibble [1 × 7]>  20  
#>  9  22.8     4  141.    95 <tibble [1 × 7]>  22.9
#> 10  19.2     6  168.   123 <tibble [1 × 7]>  18.3
#> # … with 22 more rows

Created on 2022-07-11 by the reprex package (v2.0.1)

One thing it doesn't do is remove qsec from the tibble in extra.

Upvotes: 1

Related Questions