Home > Software engineering >  How could one rename a batch of column names in R and change only one digit, leaving the rest of the
How could one rename a batch of column names in R and change only one digit, leaving the rest of the

Time:09-05

I have data from one survey with 30 items collected over two waves (i.e., time points). Items are labeled as follows: item1w1, item2w1, item3w1, etc., where w1 = wave 1. How can I rename all items by only changing the w1 to w2, leaving the rest of the item name the same as the original, without changing each item individually, as with dplyr::rename or some other method?

That is, item1w1 = item1w2, item2w1 = item2w2, etc.

CodePudding user response:

Using base R

names(df) <- sub("w1$", "w2", names(df))

CodePudding user response:

You can use rename_with:

library(dplyr)
rename_with(your_dataframe, ~ gsub("w1", "w2", .x), ends_with("w1"))
#alternative:
#rename_with(your_dataframe, ~ gsub("w1$", "w2", .x))
  • Related