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.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With