In a previous post I was shown how to swap elements of a column name around for a specific instance...
Swap elements of variable names around
Is it possible to have a more general gsub function that swaps the text occurring after the second underscore with the text occurring after the third underscore?
I have multiple column names in a dataset that look something like 'measure_subscale_wave' and I would like them to be in the format 'measure_wave_subscale'.
I have something along these lines based on the post I referenced above.
data_test <- data %>%
rename_with(
.fn = ~gsub(
pattern = 'measure_???_(.*)', # Not sure what would go on this line
replacement = '\\1_\\3_\\2',
.x
),
.cols = matches('^measure')
)