How to pivot_wider while preserving duplicate column values?

Viewed 25

looking for some help on this maybe basic issue. Suppose I have the following:

tibble(
  x= c("a","a","b","b","b","b"),
  y= c(1,2,1,2,1,2)
)

# A tibble: 6 x 2
# x         y
# <chr> <dbl>
#  1 a         1
#  2 a         2
#  3 b         1
#  4 b         2
#  5 b         1
#  6 b         2

I would like to transform to the following tibble:

tibble(
  x= c("a","b","b"),
  y.1= c("1","1","1"),
  y.2= c("2","2","2")
)

# A tibble: 3 x 3
# x     y.1   y.2  
# <chr> <chr> <chr>
# 1 a     1     2    
# 2 b     1     2    
# 3 b     1     2  

What's the best way to achieve this? I tried to use tidyr::pivot_wider but I couldn't figure it out without preserving the x column's two "b" values.

1 Answers

Given the current structure, one possible approach is to use vector recycling

library(tidyverse)
df = tibble(
  x= c("a","a","b","b","b","b"),
  y= c(1,2,1,2,1,2)
)

df %>%
  summarise(
    x = x[c(T, F)],
    y.1 = y[c(T, F)],
    y.2 = y[c(F, T)]
  )

#> # A tibble: 3 x 3
#>   x       y.1   y.2
#>   <chr> <dbl> <dbl>
#> 1 a         1     2
#> 2 b         1     2
#> 3 b         1     2

Although this could break if data is not in the proper sequence.

Related