Reputation: 147
I have the following data for example
Ind var1_1 var2_2 var3_1 var4_2.......var100_1
1 0 0 2 1 0
2 2 0 1 0 2
And I want to rename the columns without the two characters at the back as follows
Ind var1 var2 var3 var4.......var100
1 0 0 2 1 0
2 2 0 1 0 2
Upvotes: 5
Views: 2468
Reputation: 886938
We can use sub
. We match the pattern _
followed by one or more digits (\\d+
) to the end ($
) of the string and replace with ''
.
names(df) <- sub('_\\d+$', '', names(df))
Or as @David Arenburg mentioned, it can be one or more of any character (.*
) after the _
(which will match patterns such var1_1
, var1_d3533
etc.)
names(df) sub("_.*", "", df)
Or we use paste
(@jogo's comment)
names(df) <- c("Ind", paste0("var", 1:100))
Upvotes: 7