Removing suffix from column names using rename_all?

linda picture linda · Aug 30, 2017 · Viewed 10.9k times · Source

I have a data frame with a number of columns in a form var1.mean, var2.mean. I would like to strip the suffix ".mean" from all columns that contain it. I tried using rename_all in conjunction with regex in a pipe but could not come up with a correct syntax. Any suggestions?

Answer

Benjamin picture Benjamin · Aug 30, 2017

If you want to use the dplyr package, I'd recommend using the rename_at function.

Dframe <- data.frame(var1.mean = rnorm(10),
                     var2.mean = rnorm(10),
                     var1.sd = runif(10))

library(dplyr)

Dframe %>% 
  rename_at(.vars = vars(ends_with(".mean")),
            .funs = funs(sub("[.]mean$", "", .)))