user8959427
user8959427

Reputation: 2067

Using rename_all to remove numbers from column names

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

Answers (2)

Ric S
Ric S

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

Ronak Shah
Ronak Shah

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

Related Questions