linda linda - 3 years ago 194
R Question

Removing suffix from column names using rename_all?

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 Source

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$", "", .)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download