To delete characters in column names

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 columns without two characters at the back:

Ind var1 var2 var3 var4.......var100
 1   0     0    2    1           0
 2   2     0    1    0           2
+4
source share
1 answer

We can use sub. We match the pattern _, followed by one or more digits ( \\d+) to the end ( $) of the line, and replace it with ''.

names(df) <- sub('_\\d+$', '', names(df))

Or, as @David Arenburg mentioned, it can be one or more characters ( .*) after _(which will match patterns such as var1_1, var1_d3533etc.)

names(df) sub("_.*", "", df)

Or we use paste(comment by @jogo)

names(df) <- c("Ind", paste0("var", 1:100))
+7
source

Source: https://habr.com/ru/post/1622936/


All Articles