How to divide the row values by row sum in data.table object in R?

R ProgrammingServer Side ProgrammingProgramming

To divide the row values by row sum in R’s data.table object, we can follow the below steps −

  • First of all, create a data.table object.
  • Then, use apply function to divide the data.table object row values by row sum.

Create the data.table object

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

library(data.table)
x<-rpois(25,2)
y<-rpois(25,2)
DT<-data.table(x,y)
DT

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

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

Divide the data.table object row values by row sum

Using apply function to divide the row values of DT by row sum −

library(data.table)
x<-rpois(25,2)
y<-rpois(25,2)
DT<-data.table(x,y)
DT_new<-t(apply(DT,1, function(x) x/sum(x)))
DT_new

Output

         x          y
[1,] 0.5714286 0.4285714
[2,] 0.0000000 1.0000000
[3,] 0.3333333 0.6666667
[4,] 0.5000000 0.5000000
[5,] 1.0000000 0.0000000
[6,] 0.4000000 0.6000000
[7,] 0.0000000 1.0000000
[8,] 0.3333333 0.6666667
[9,] 1.0000000 0.0000000
[10,] 0.3333333 0.6666667
[11,] 0.2000000 0.8000000
[12,] 0.2000000 0.8000000
[13,] 0.8000000 0.2000000
[14,] 0.2500000 0.7500000
[15,] 0.3333333 0.6666667
[16,] 0.2500000 0.7500000
[17,] 0.5000000 0.5000000
[18,] 0.0000000 1.0000000
[19,] 0.0000000 1.0000000
[20,] 0.3333333 0.6666667
[21,] 0.5000000 0.5000000
[22,] 1.0000000 0.0000000
[23,] 0.6666667 0.3333333
[24,] 0.5000000 0.5000000
[25,] 0.5000000 0.5000000
raja
Published on 05-Aug-2021 13:19:51
Advertisements