Reputation: 339
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
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"
v1 <- c('Sales_Ab', 'Cost_Bcfg', 'Revenue_Cshsh')
Upvotes: 1