krakkor
krakkor

Reputation: 33

remove part from middle of column names in R

New to R, would like to remove a useless part from the column names in my data frame

df <- data.frame(column.0.1 = c(1,2,3,4,5),
                column.0.2 = c(1,2,3,4,5), 
                column.0.3 = c(1,2,3,4,5))
#i have tried
colnames(df) <- sub('\\.[^.]+$', '', colnames(df))
colnames(df)

[1] "column.0" "column.0" "column.0"

#Instead, I want to remove the useless 0 in the middle of the column names so the result would be

[1] "column.1" "column.2" "column.3"

Many thanks!

Upvotes: 3

Views: 174

Answers (1)

Greg
Greg

Reputation: 3670

If your names all just have an extra ".0" you were very close:

colnames(df) <- sub('\\.0', '', colnames(df))
colnames(df)
[1] "column.1" "column.2" "column.3"

Upvotes: 1

Related Questions