Better way to pivot longer?

It can be done by using the .value special name as the first argument in names_to.

library(tidyverse)

df <- tibble(key = 1:2, 
             x_1 = paste("x", 1:2, sep = ""), 
             x_2 = paste("x", 3:4, sep = ""), 
             y_1 = paste("y", 1:2, sep = ""), 
             y_2 = paste("y", 3:4, sep = ""), 
             z_1 = paste("z", 1:2, sep = ""), 
             z_2 = paste("z", 3:4, sep = ""))

pivot_longer(df, cols = -key, names_to = c(".value", "rep"), names_pattern = ("(.)_(.)"))
#> # A tibble: 4 x 5
#>     key rep   x     y     z    
#>   <int> <chr> <chr> <chr> <chr>
#> 1     1 1     x1    y1    z1   
#> 2     1 2     x3    y3    z3   
#> 3     2 1     x2    y2    z2   
#> 4     2 2     x4    y4    z4

Created on 2020-06-04 by the reprex package (v0.3.0)

3 Likes