Skip to content

pivot_wider() with values_from a data frame column #926

@mikmart

Description

@mikmart

It seems like values get mixed up and replicated when pivoting to wider from a data frame column:

library(tidyr)

tbl <- tibble(
  i = c(1, 2, 1, 2),
  g = c("a", "a", "b", "b"),
  d = tibble(x = 1:4, y = 5:8)
)

tbl
#> # A tibble: 4 x 3
#>       i g       d$x    $y
#>   <dbl> <chr> <int> <int>
#> 1     1 a         1     5
#> 2     2 a         2     6
#> 3     1 b         3     7
#> 4     2 b         4     8

tbl %>% 
  pivot_wider(
    names_from = g,
    values_from = d
  )
#> # A tibble: 2 x 3
#>       i   a$x    $y   b$x    $y
#>   <dbl> <int> <int> <int> <int>
#> 1     1     1     5     2     6
#> 2     2     1     5     2     6

# expected to get
tibble(
  i = c(1, 2),
  a = tibble(x = 1:2, y = 5:6),
  b = tibble(x = 3:4, y = 7:8)
)
#> # A tibble: 2 x 3
#>       i   a$x    $y   b$x    $y
#>   <dbl> <int> <int> <int> <int>
#> 1     1     1     5     3     7
#> 2     2     2     6     4     8

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviorpivoting ♻️pivot rectangular data to different "shapes"

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions