Swap elements of a column name using gsub

Viewed 20

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')
  )
1 Answers

You can use

data_test <- data %>% 

  rename_with(
    .fn = ~gsub(
      pattern = '(measure)_(.*)_(.*)'
      replacement = '\\1_\\3_\\2',
      .x
    ), 
    .cols = matches('^measure')
  )

Here,

  • (measure) - Group 1 (\1): a measure word
  • _ - an underscore
  • (.*) - Group 2 (\2): any zero or more chars other than line break chars as many as possible
  • _ - an underscore
  • (.*) - Group 3 (\3): any zero or more chars other than line break chars as many as possible
Related