Reputation: 2067
I am trying to remove the numbers from some column names that I have. I have tried the following without luck.
iris %>%
rename_all(.funs = list(gsub('[[:digit:]]+', "", names(.))))
How can I use rename_all
to remove the numbers from the column names correctly?
Data:
data(iris)
numericNames <- paste(seq(1:5), colnames(iris), sep = "")
colnames(iris) <- numericNames
Upvotes: 2
Views: 726
Reputation: 9247
Since the scoped variant rename_all
has been superseded as of dplyr
version 1.0.0, you should use rename_with
like this:
iris %>%
rename_with(~gsub("\\d+", "", .))
or, using the regular expression you used
iris %>%
rename_with(~gsub('[[:digit:]]+', "", .))
The .
refers to the name of the column, so you don't need to use names(.)
Output
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# ...
Upvotes: 4
Reputation: 388982
In rename_all
column names are passed directly.
library(dplyr)
iris %>% rename_all(~gsub('[[:digit:]]+', "", .)) %>% head
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1 5.1 3.5 1.4 0.2 setosa
#2 4.9 3.0 1.4 0.2 setosa
#3 4.7 3.2 1.3 0.2 setosa
#4 4.6 3.1 1.5 0.2 setosa
#5 5.0 3.6 1.4 0.2 setosa
#6 5.4 3.9 1.7 0.4 setosa
Upvotes: 1