I am looking for a way to multiply several columns of a data.table
by several other columns in the same DT. Another post focused on the way to multiply many columns by a specific column in the same DT Multiply many columns by a specific other column in R with data.table?. My question broadens this prior question.
Starting with this DT:
DT <- data.table(x1 = 1:5L, y1 = 6:10L, x2 = 11:15L, y2 = 16:20L)
x1 y1 x2 y2
1: 1 6 11 16
2: 2 7 12 17
3: 3 8 13 18
4: 4 9 14 19
5: 5 10 15 20
I want to multiply z1 = x1 * y1
, and z2 = x2 * y2
to obtain
x1 y1 x2 y2 z1 z2
1: 1 6 11 16 6 176
2: 2 7 12 17 14 204
3: 3 8 13 18 24 234
4: 4 9 14 19 36 266
5: 5 10 15 20 50 300
Here is a brute force way of building the desired DT:
DT2[, ':='(z1 = x1 * y1, z2 = x2 * y2]
Certainly there must be an elegant way to do this.