SJDS SJDS - 6 months ago 32
R Question

Add letter to setnames in data.table R

What is the simplest way to change the colnames of a data.table in such a way that the original name is kept but preceded (or followed) by one or a few other letters.
E.g. I'm running the following code

tmp <- DT[, lapply(.SD, mean, na.rm=T), by = .(NACE2), .SDcols=cols]
tmp1 <- DT[, lapply(.SD, sum, na.rm=T), by = .(NACE2), .SDcols=cols]
sna <- function(x) { sum(!}
tmp2 <- DT[, lapply(.SD, sna), by = .(NACE2), .SDcols=cols]

This results in multiple data.tables which all have the same names determined by the original names in
, which has 65 selected columns via

I would like to change the colnames before merging
tmp, tmp1, tmp2
together in such a way that the names are preceded respectively by

  1. m_ for

  2. s_ for

  3. na_ for

Is there a way of doing this directly in the
function or a better way than avoiding retyping 65 names via
setnames(tmp, ...)
I know it is possible to create a vector of the colnames and then combine that vector with another vector consisting of e.g. "m_" but there must be a more sensible way.


We can use paste with setnames to change the column names

setnames(tmp, paste0("m_", names(tmp)))

and similarly

setnames(tmp1, paste0("s_", names(tmp1)))
setnames(tmp2, paste0("na_", names(tmp2)))