Skip to content

pack() / unpack() #523

@romainfrancois

Description

@romainfrancois
  • pack() would tidy select columns, pack them in a data frame and then add that data frame as a new column
  • unpack() would "promote" columns from a data frame columns as columns of the outer df.

(very sketchy, just unloading pack from my head)

library(tidyverse)

pack <- function(.tbl, name = "data", ...) {
  all_vars <- tbl_vars(.tbl)
  selected <- tidyselect::vars_select(all_vars, ...)
  not_selected <- setdiff(all_vars, selected)
  
  .tbl %>% 
    select(not_selected) %>% 
    add_column(!!name := select(.tbl, selected))
}

df <- iris %>% 
  as_tibble() %>% 
  pack("Sepal", Length = Sepal.Length, Width = Sepal.Width) %>% 
  pack("Petal", Length = Petal.Length, Width = Petal.Width)
df$Petal
#> # A tibble: 150 x 2
#>    Length Width
#>     <dbl> <dbl>
#>  1    1.4   0.2
#>  2    1.4   0.2
#>  3    1.3   0.2
#>  4    1.5   0.2
#>  5    1.4   0.2
#>  6    1.7   0.4
#>  7    1.4   0.3
#>  8    1.5   0.2
#>  9    1.4   0.2
#> 10    1.5   0.1
#> # … with 140 more rows

Created on 2018-12-13 by the reprex package (v0.2.1.9000)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions