user36176
user36176

Reputation: 339

interchange variable names based on a separator in R

I have variable names

Sales_Ab Cost_Bcfg Revenue_Cshsh

I would like the output data to look like

Ab_Sales Bcfg_Cost Cshsh_Revenue

Im aware sub and gsub can be used in some form but Im not versed with the exact technicality required to code that.

Upvotes: 0

Views: 95

Answers (1)

akrun
akrun

Reputation: 887601

We use sub to match the first word, capture as a group ((\\w+)) followed by a _ and then capture the next word ((...)), replace it with the backreference. Here we switch the order of the backreference to 2nd backreference followed by the _ and then the 1st.

sub("(\\w+)_(\\w+)", '\\2_\\1', v1)
#[1] "Ab_Sales"      "Bcfg_Cost"     "Cshsh_Revenue"

data

v1 <- c('Sales_Ab',  'Cost_Bcfg', 'Revenue_Cshsh')

Upvotes: 1

Related Questions