How to find the row total of columns having same name in data.table object in R?

To find the row total of columns having same name in data.table object in R, we can follow the below steps −

• First of all, create a data.table with some columns having same name.

• Then, use tapply along with colnames and sum function to find the row total of columns having same name.

Example

Create the data.table

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

library(data.table)
DT<-
data.table(x=rpois(25,5),y=rpois(25,10),x=rpois(25,5),y=rpois(25,2),check.names=FALSE)
DT

Output

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

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

Find the row total of columns having same name

Using tapply along with colnames and sum function to find the row total of columns having same name in data.table object DT −

library(data.table)
DT<-
data.table(x=rpois(25,5),y=rpois(25,10),x=rpois(25,5),y=rpois(25,2),check.names=FALSE)
t(apply(DT,1, function(x) tapply(x,colnames(DT),sum)))

Output

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

Updated on: 16-Nov-2021

95 Views