Search code examples
rdataframedplyrwildcardcalculated-columns

R remove suffix from variable names in data frame


I'm trying to remove suffix to variable names of a data frame in R to aggregate this columns.

I've imported a excel sheet into a data frame in R, but the column names where imported like this

var1...9   var2...10   var1...11   var2...12   var3.name...13
      12           7           5          10                6
       3           9          20           7               13

What I need is to remove the last part (from ...) to aggregate the columns by name.

var1   var2   var3.name
  17     17           6
  23     16          13

To do this I'm using dplyr

library(dplyr)
x %>% 
  rename_at(.vars = vars(ends_with("...*")),
            .funs = funs(sub("[...]*$", "", .)))

but doesn't work, I think using * is not the appropriate way to use a wildcard...


Solution

  • I actually think using base R is easier here:

    names(x) <- sub("\\.{3}\\d*$", "", names(x))