How to find the sum of rows of a column based on multiple columns in R’s data.table object?


To find the sum of rows of a column based on multiple columns in R’s data.table object, we can follow the below steps−

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

  • Then, use aggregate function to find the sum of rows of a column based on multiple columns.

Example

Create the data.table object

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

library(data.table)
F1<-sample(c("Male","Female"),25,replace=TRUE)
F2<-sample(c("Low","Medium","High"),25,replace=TRUE)
F3<-sample(c("I","II","III"),25,replace=TRUE)
Response<-sample(1:100,25)
DT<-data.table(F1,F2,F3,Response)
DT

Output

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

     F1     F2    F3 Response
1:  Male   Medium  I    2
2:  Female Low     I   32
3:  Female High   II   43
4:  Male   Medium  I   24
5:  Male   Medium III  88
6:  Female High    I   95
7:  Male   Low    II   68
8:  Female High    I   74
9:  Female High   II   12
10: Male   High   III  42
11: Male   High   I    62
12: Male   High   III  67
13: Female High   III  38
14: Male   Low    III  73
15: Female Low    III   3
16: Male   Medium III  98
17: Female Low     I  100
18: Male   Medium  II  89
19: Female High    II  81
20: Female Low      I  53
21: Female Medium  II  91
22: Female High    II  63
23: Female High    II  60
24: Male   Medium  II  72
25: Female Medium  III 56
    F1      F2     F3 Response

Find the sum of rows of a column based on multiple columns

Using aggregate function to find the sum of rows of column Response based on columns F1, F2, and F3 as shown below −

library(data.table)
F1<-sample(c("Male","Female"),25,replace=TRUE)
F2<-sample(c("Low","Medium","High"),25,replace=TRUE)
F3<-sample(c("I","II","III"),25,replace=TRUE)
Response<-sample(1:100,25)
DT<-data.table(F1,F2,F3,Response)
DT[,sum(Response),by=.(F1,F2,F3)]

Output

     F1     F2    F3   V1
1:  Male   Medium I    26
2:  Female Low    I   185
3:  Female High   II  259
4:  Male   Medium III 186
5:  Female High   I   169
6:  Male   Low    II   68
7:  Male   High   III 109
8:  Male   High   I   62
9:  Female High   III 38
10: Male   Low    III 73
11: Female Low    III  3
12: Male   Medium II 161
13: Female Medium II  91
14: Female Medium III 56

Updated on: 12-Nov-2021

898 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements