How to multiply corresponding values from two data.table objects in R?



To multiply corresponding values from two data.table objects in R, we can follow the below steps −

  • First of all, create two data.table objects.

  • Then, use mapply function to multiply corresponding values from those two data.table objects.

Example

Create the first data.table object

Let’s create a data.table object as shown below −

library(data.table) x1<-sample(1:50,25) x2<-sample(1:50,25) x3<-sample(1:50,25) DT1<-data.table(x1,x2,x3) DT1

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   x1 x2 x3 1: 27 39 33 2: 44 24 36 3: 19 50 40 4: 38 20 42 5: 33 29 26 6: 16 42 41 7: 21 6 22 8:  42 47 5 9:   8 33 34 10:  6 13 24 11: 12 4 29 12: 7 11 48 13: 15 15 27 14: 9 40 9 15: 46 34 17 16: 26 14 21 17: 20 19 1 18: 22 27 13 19: 36 16 23 20: 28 26 6 21: 37 41 46 22: 24 46 2 23: 49 32 10 24: 17 35 19 25: 47 31 3     x1 x2 x3

Create the first data.table object

Let’s create a data.table object as shown below −

y1<-sample(1:50,25) y2<-sample(1:50,25) y3<-sample(1:50,25) DT2<-data.table(y1,y2,y3) DT2

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

    y1 y2 y3 1:  35 45 30 2:  28 50 10 3:  33 35  8 4:  48 15 26 5:  43 39 37 6:  25 48 32 7:  15 40 44 8:  38 25 12 9:  13 33 16 10:  1 37 14 11: 23 31 13 12: 44  4 46 13: 40 22 15 14: 47 23 31 15: 29 18 48 16: 49 26 17 17: 42 30  2 18: 32 38  4 19: 22 29 28 20: 24 16 41 21: 19 11 42 22: 36 34  9 23: 14  6  1 24: 18 14 23 25: 31 19 11    y1 y2 y3

Multiply corresponding values from two data.table objects

library(data.table) x1<-sample(1:50,25) x2<-sample(1:50,25) x3<-sample(1:50,25) DT1<-data.table(x1,x2,x3) y1<-sample(1:50,25) y2<-sample(1:50,25) y3<-sample(1:50,25) DT2<-data.table(y1,y2,y3) mapply(`*`,DT1,DT2)

Output

       1    x2    x3 [1,]  945  1755   990 [2,]  1232 1200   360 [3,]  627  1750   320 [4,]  1824  300  1092 [5,]  1419 1131   962 [6,]  400  2016  1312 [7,]  315   240   968 [8,]  1596 1175    60 [9,]  104  1089   544 [10,]  6    481   336 [11,] 276   124   377 [12,] 308    44  2208 [13,] 600   330   405 [14,] 423   920   279 [15,] 1334  612   816 [16,] 1274  364   357 [17,] 840   570     2 [18,] 704  1026    52 [19,] 792   464   644 [20,] 672   416   246 [21,] 703   451  1932 [22,] 864  1564    18 [23,] 686   192    10 [24,] 306   490   437 [25,] 1457  589    33
Updated on: 2021-11-10T07:33:11+05:30

554 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements