This seems to work:
dt[ , (cols) := lapply(.SD, "*", -1), .SDcols = cols]
The result is
a b d
1: -1 -1 1
2: -2 -2 2
3: -3 -3 3
There are a few tricks here:
- Because there are parentheses in
(cols) :=, the result is assigned to the columns specified incols, instead of to some new variable named “cols”. .SDcolstells the call that we’re only looking at those columns, and allows us to use.SD, theSubset of theData associated with those columns.lapply(.SD, ...)operates on.SD, which is a list of columns (like all data.frames and data.tables).lapplyreturns a list, so in the endjlooks likecols := list(...).
EDIT: Here’s another way that is probably faster, as @Arun mentioned:
for (j in cols) set(dt, j = j, value = -dt[[j]])