How to rename columns with pattern in R?

53 Views Asked by At
df <- data.frame(
  ID_1 = 1:5,
ID_2 = 1:5,
ID_3 = 1:5,
ID_4 = 1:5)

I want to replace each column with "participantID_" and a digit that has a value of +1 of the digit in the original columns.

As follows:

ID_1 should be participantID_2, ID_2 should be participantID_3...

How can I achieve this?

1

There are 1 best solutions below

1
thelatemail On

regexpr to match the number, regmatches to extract it, and then overwrite the original names(df):

names(df) <- paste0("ParticipantID_",
                    as.numeric(regmatches(names(df), regexpr("\\d$", names(df)))) + 1)
df
#  ParticipantID_2 ParticipantID_3 ParticipantID_4 ParticipantID_5
#1               1               1               1               1
#2               2               2               2               2
#3               3               3               3               3
#4               4               4               4               4
#5               5               5               5               5