• First of all, create a data.table object.

  • Then, using plus sign (+) to add two rows and store the addition i">

    How to combine two rows in data.table object in R by addition?



    To combine two rows in data.table object in R by addition, we can follow the below steps −

    • First of all, create a data.table object.

    • Then, using plus sign (+) to add two rows and store the addition in one of the rows.

    • After that, remove the row that is not required by subsetting with single square brackets.

    Example

    Create the data.table object

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

    library(data.table) x<-sample(1:5,25,replace=TRUE) y<-sample(1:5,25,replace=TRUE) z<-sample(1:5,25,replace=TRUE) DT<-data.table(x,y,z) DT

    Output

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

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

    Add two rows

    Using plus sign to add row 1 and row 2 then storing the sum in row 1 −

    library(data.table) x<-sample(1:5,25,replace=TRUE) y<-sample(1:5,25,replace=TRUE) z<-sample(1:5,25,replace=TRUE) DT<-data.table(x,y,z) DT[1,]<-DT[1,]+DT[2,] DT

    Output

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

    Remove the row which is not required

    Using single square subsetting to remove 2nd row from data.table object DT −

    library(data.table) x<-sample(1:5,25,replace=TRUE) y<-sample(1:5,25,replace=TRUE) z<-sample(1:5,25,replace=TRUE) DT<-data.table(x,y,z) DT[1,]<-DT[1,]+DT[2,] DT[-2,]

    Output

        x y z
    1:  5 5 5
    2:  3 3 1
    3:  1 1 1
    4:  1 1 1
    5:  5 2 3
    6:  2 5 1
    7:  2 5 4
    8:  4 1 1
    9:  1 3 2
    10: 1 3 5
    11: 4 5 2
    12: 4 4 1
    13: 2 1 5
    14: 1 5 2
    15: 3 4 4
    16: 5 5 4
    17: 2 2 5
    18: 1 4 5
    19: 4 5 5
    20: 4 1 1
    21: 5 5 2
    22: 4 1 4
    23: 1 2 3
    24: 4 3 1
        x y z
    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements