R .SD inplace multiplication to multiple columns

46 Views Asked by At

Let's assume I have the mtcars dataset and I need to multiply columns hp, drat, wt and qsec by some adjusting factor whenever cyl==6.

mtcars = data.table(mtcars)
mtcars$adjusting_factor = rnorm(nrow(mtcars), mean=1, sd=0.2) #Factor to multiply the columns

    mpg cyl disp  hp drat    wt  qsec vs am gear carb adjusting_factor
1: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4        1.2522949
2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4        1.1783525
3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1        0.9486466
4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1        0.7600410
5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2        0.9379801
6: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1        0.9970463

I can get the needed values with:

mtcars[cyl==6, lapply(.SD, `*`, adjusting_factor), .SDcols = hp:qsec]

          hp     drat       wt     qsec
1: 137.75244 4.883950 3.281013 20.61277
2: 129.61878 4.595575 3.387764 20.05556
3:  83.60451 2.340926 2.443532 14.77520
4: 104.68987 2.751848 3.449780 20.16028
5: 172.40582 5.494559 4.821756 25.65062
6: 131.71432 4.197725 3.683718 20.23903
7: 214.46022 4.436263 3.394599 18.99505

However, I don't know how save these values inplace while keeping all the other rows where cyl is not 6 and all the other columns (e.g. mpg, dist) the same. How do I assign the result above inplace?

I tried multiple combinations like the one below but to no avail.

change_cols = colnames(mtcars)[4:7]
mtcars2 = mtcars[cyl==6, change_cols := lapply(.SD, `*`, gear), .SDcols = change_cols]
0

There are 0 best solutions below