Reputation: 47
Is it possible to add a prefix to the column names that are generated from using the .value
option in the argument names_to
in pivot_longer
?
Example:
df <- tibble(x1 = 0.1, x2 = 0.2, y1 = 0.05, y2 = 0.15)
df %>%
pivot_longer(cols = everything(),
names_to = c('coord_type', '.value'),
names_pattern = '(\\D+)(\\d+)')
# A tibble: 2 × 3
coord_type `1` `2`
<chr> <dbl> <dbl>
1 x 0.1 0.2
2 y 0.05 0.15
I would like the 1
and 2
columns to have prefixes "coord_" in front of them. Of course, I could simply rename them after the pivot_longer like so:
df %>%
pivot_longer(cols = everything(),
names_to = c('coord_type', '.value'),
names_pattern = '(\\D+)(\\d+)') %>%
rename_with(.fn = ~glue("coord_{.x}"), matches("[12]"))
# A tibble: 2 × 3
coord_type coord_1 coord_2
<chr> <dbl> <dbl>
1 x 0.1 0.2
2 y 0.05 0.15
But I'm interested if pivot_longer
has some option to do so concisely.
Upvotes: 2
Views: 122
Reputation: 887158
We could use names_repair
, which can take a function
library(stringr)
library(tidyr)
pivot_longer(df, cols = everything(),
names_to = c('coord_type', '.value'),
names_pattern = '(\\D+)(\\d+)',
names_repair = ~ str_replace(.x, "^(\\d+)", "coord_\\1"))
-output
# A tibble: 2 × 3
coord_type coord_1 coord_2
<chr> <dbl> <dbl>
1 x 0.1 0.2
2 y 0.05 0.15
Upvotes: 2