Data.table setnames combined with regex

I would like to rename each column in the data table based on the regular expression accordingly.

library(data.table)
DT <- data.table("a_foo" = 1:2, "bar_b" = 1:2)
   a_foo bar_b
1:     1     1
2:     2     2

I would like to strip "_foo" and "bar_" from the names. This classic line does the trick, but also copies the entire table.

names(DT) <- gsub("_foo|bar_", "", names(DT))

How can I do the same with setnames()? I have many variables, so just writing all the names is not an option.

+4
source share
1 answer

You can try

setnames(DT, names(DT), gsub("_foo|bar_", "", names(DT)))

based on use in ?setnamesiesetnames(x,old,new)

Or as @eddi commented

setnames(DT, gsub("_foo|bar_", "", names(DT)))
+8
source

All Articles