• First of all, create a data.table object with multiple rows and a data.tabl">

    How to multiply corresponding row values in a data.table object with single row data.table object in R?



    To multiply row values in a data.table object having multiple rows with single row data.table object in R, we can follow the below steps −

    • First of all, create a data.table object with multiple rows and a data.table object with single row.

    • Then, use mapply function to multiply row values in those objects.

    Example

    Create the first data.table object

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

    library(data.table)
    x1<-sample(1:10,25,replace=TRUE)
    x2<-sample(1:10,25,replace=TRUE)
    DT1<-data.table(x1,x2)
    DT1

    Output

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

         x1 x2
    1:   8  1
    2:   4  2
    3:   8  5
    4:   4  1
    5:  10  2
    6:   5 10
    7:   9  3
    8:   6  5
    9:   1  6
    10:  7  1
    11:  9  7
    12:  8  9
    13:  4 10
    14: 10  6
    15:  1  4
    16:  8  1
    17: 10  4
    18:  7  1
    19:  3  1
    20:  3  7
    21:  2  8
    22:  4  9
    23:  5  8
    24:  4  7
    25:  3  1
        x1 x2

    Create the second data.table object

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

    DT2<-data.table(y1=5,y2=0)
    DT2

    Output

       y1 y2
    1: 5  0

    Multiply values from two data.table objects

    Using mapply function to multiply row values in the data.table object DT1 having multiple rows with single row data.table object DT2 −

    library(data.table)
    x1<-sample(1:10,25,replace=TRUE)
    x2<-sample(1:10,25,replace=TRUE)
    DT1<-data.table(x1,x2)
    DT2<-data.table(y1=5,y2=0)
    mapply(`*`,DT1,DT2)

    Output

           x1 x2
    [1,]   40 0
    [2,]   20 0
    [3,]   40 0
    [4,]   20 0
    [5,]   50 0
    [6,]   25 0
    [7,]   45 0
    [8,]   30 0
    [9,]    5 0
    [10,]  35 0
    [11,]  45 0
    [12,]  40 0
    [13,]  20 0
    [14,]  50 0
    [15,]   5 0
    [16,]  40 0
    [17,]  50 0
    [18,]  35 0
    [19,]  15 0
    [20,]  15 0
    [21,]  10 0
    [22,]  20 0
    [23,]  25 0
    [24,]  20 0
    [25,]  15 0
    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements