Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply a number of columns by a specific column [duplicate]

Tags:

r

data.table

I have a data frame with several columns containing different areas by location. In another column I have a density value. I would like to know how to create a new table (ideally through a loop) with each area multiplied by the density. My data frame looks like:

X   Area1  Area2  Area3  Area4 Density
A   10.1    12     20     25    0.04
B   4.2     7.3    30     35    0.05
C   5.3     9.6    10     15    0.07
D   0.2     0.3    2      3     0.01

I have seem a similar question at: Multiply many columns by a specific other column in R with data.table? but cannot figure out a way to adapt it to work for my data. Many thanks :)

like image 205
user3489562 Avatar asked Jan 24 '26 08:01

user3489562


1 Answers

If dt is your data.table then

dtcopy <- copy(dt)
dtcopy[, 2:5 := lapply(.SD, '*', Density), .SDcols = 2:5][]

gives the following result:

> dtcopy
   X Area1 Area2 Area3 Area4 Density
1: A 0.404 0.480  0.80  1.00    0.04
2: B 0.210 0.365  1.50  1.75    0.05
3: C 0.371 0.672  0.70  1.05    0.07
4: D 0.002 0.003  0.02  0.03    0.01

While your original data.table dt is still unchanged because you used the copy-function to make a copy:

> dt
   X Area1 Area2 Area3 Area4 Density
1: A  10.1  12.0    20    25    0.04
2: B   4.2   7.3    30    35    0.05
3: C   5.3   9.6    10    15    0.07
4: D   0.2   0.3     2     3    0.01

See also Understanding exactly when a data.table is a reference to (vs a copy of) another data.table on why you need to use copy.


Used data:

library(data.table)
dt <- fread('X   Area1  Area2  Area3  Area4 Density
             A   10.1    12     20     25    0.04
             B   4.2     7.3    30     35    0.05
             C   5.3     9.6    10     15    0.07
             D   0.2     0.3    2      3     0.01')
like image 123
Jaap Avatar answered Jan 25 '26 22:01

Jaap