Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to delete characters in column names

Tags:

r

rename

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
like image 788
Shima Avatar asked Jan 05 '16 15:01

Shima


People also ask

How do I delete column names?

Select the column header, and then select Column settings > Format this column. Select any column header, and then select Column settings > Show/hide columns. Select the column header you want to delete and select Column settings > Edit > Delete.

How do I rename multiple column names?

To change multiple column names by name and by index use rename() function of the dplyr package and to rename by just name use setnames() from data. table . From R base functionality, we have colnames() and names() functions that can be used to rename a data frame column by a single index or name.

How do I remove a character from a column in a DataFrame in R?

Use gsub() function to remove a character from a string or text in R. This is an R base function that takes 3 arguments, first, the character to look for, second, the value to replace with, in our case we use blank string, and the third input string were to replace.


1 Answers

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))
like image 56
akrun Avatar answered Nov 14 '22 16:11

akrun