Skip to content

unnest multiple columns #740

@moodymudskipper

Description

@moodymudskipper

See #737 for full example

Given the overall extreme flexibility of the new functions I was surprised that unnest_wider doesn't allow unnesting several columns.

library(tidyverse)
df2 <- tibble::tribble(
  ~id, ~var1,              ~Country,                        ~Sport,             ~Format,
  10L,  169L, c("Norway", "Sweden"),                        "Skii", c("Video", "Photo"),
  11L,  150L,               "Spain", c("Bike", "Soccer", "Basket"),             "Photo",
  12L,    0L,                 "USA",                    "Baseball",             "Video"
)

df2 %>%
  unnest_wider(Country, names_sep = "_") %>%
  unnest_wider(Sport, names_sep = "_") %>%
  unnest_wider(Format, names_sep = "_")
#> New names:
#> * `` -> ...1
#> * `` -> ...2
#> New names:
#> * `` -> ...1
#> New names:
#> * `` -> ...1
#> New names:
#> * `` -> ...1
#> New names:
#> * `` -> ...1
#> * `` -> ...2
#> * `` -> ...3
#> New names:
#> * `` -> ...1
#> New names:
#> * `` -> ...1
#> * `` -> ...2
#> New names:
#> * `` -> ...1
#> New names:
#> * `` -> ...1
#> # A tibble: 3 x 9
#>      id  var1 Country_...1 Country_...2 Sport_...1 Sport_...2 Sport_...3
#>   <int> <int> <chr>        <chr>        <chr>      <chr>      <chr>     
#> 1    10   169 Norway       Sweden       Skii       <NA>       <NA>      
#> 2    11   150 Spain        <NA>         Bike       Soccer     Basket    
#> 3    12     0 USA          <NA>         Baseball   <NA>       <NA>      
#> # ... with 2 more variables: Format_...1 <chr>, Format_...2 <chr>

If I didn't want to enumerate explicitly I could design a complex reduce call but it would be neat to be able to just call :

df2 %>%
  unnest_wider(one_of("Country","Sport", "Format"), names_sep = "_")

In case this isn't acceptable, I think we could use a more helpful message than

Error in .subset2(x, i) : no such index at level 2

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurea feature request or enhancementrectangling 🗄️converting deeply nested lists into tidy data frames

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions