Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data.table setnames combined with regex

I would like to rename each column in a data table based on a regex in an appropriate way.

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 cut the "_foo" and "bar_" from the names. This classic line does the trick, but it also copies the whole table.

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

How can I do the same using setnames()? I have a lots of variables, so just writing out all of the names is not an option.

like image 983
janosdivenyi Avatar asked Feb 24 '15 16:02

janosdivenyi


1 Answers

You could try

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

based on the usage in ?setnames i.e. setnames(x,old,new)

Or as @eddi commented

setnames(DT, gsub("_foo|bar_", "", names(DT)))
like image 197
akrun Avatar answered Nov 17 '22 20:11

akrun