cory
cory

Reputation: 49

How could one rename a batch of column names in R and change only one digit, leaving the rest of the name the same?

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.

Upvotes: 1

Views: 73

Answers (2)

akrun
akrun

Reputation: 887148

Using base R

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

Upvotes: 4

Ma&#235;l
Ma&#235;l

Reputation: 52004

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))

Upvotes: 4

Related Questions