As noted in
Reshaping multiple sets of measurement columns (wide format) into single columns (long format) and
Elegant solution for casting (spreading) multiple columns of character vectors,
you can use the ".value"
component of the names_to argument in tidyr's pivot_wider() to make multiple columns longer at once:
tibble(
name = LETTERS[1:10],
a_x = 1:10,
a_y = -1:-10,
b_x = 1:10,
b_y = -1:-10,
c_x = 1:10,
c_y = -1:-10,
d_x = 1:10,
d_y = -1:-10
) %>%
pivot_longer(
cols = -name,
names_to = c(".value", "group"),
names_sep = "_",
)
which produces this:
# A tibble: 20 x 6
name group a b c d
<chr> <chr> <int> <int> <int> <int>
1 A x 1 1 1 1
2 A y -1 -1 -1 -1
3 B x 2 2 2 2
4 B y -2 -2 -2 -2
5 C x 3 3 3 3
6 C y -3 -3 -3 -3
7 D x 4 4 4 4
8 D y -4 -4 -4 -4
9 E x 5 5 5 5
10 E y -5 -5 -5 -5
11 F x 6 6 6 6
12 F y -6 -6 -6 -6
13 G x 7 7 7 7
14 G y -7 -7 -7 -7
15 H x 8 8 8 8
16 H y -8 -8 -8 -8
17 I x 9 9 9 9
18 I y -9 -9 -9 -9
19 J x 10 10 10 10
20 J y -10 -10 -10 -10
This is useful, but it presumes that the suffix provides the grouping component on which to pivot. However, sometimes one might want to pivot on the prefix, for instance where abcd would go in the group column and xy would be the two columns.
This was apparently talked about in the original discussion around this feature here but if there's a solution to implement it I can't seem to make any headway.
I can do this other ways, for instance with base reshape() and varying, or with creating a pivoting specification, but can this be done cleanly with this tool?