How to divide rows in a data.table object by row variance in R?

R ProgrammingServer Side ProgrammingProgramming

To divide the row values by row variance 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 variance.

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

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

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

Divide the data.table object row values by row variance

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

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_new<-t(apply(DT,1, function(x) x/var(x)))
DT_new

Output

         x          y         z
[1,]  6.0000000 6.0000000 3.0000000
[2,]  9.0000000 12.0000000 9.0000000
[3,]  0.8571429 2.1428571 1.2857143
[4,]  2.0000000 4.0000000 3.0000000
[5,]  0.7500000 1.2500000 0.2500000
[6,]  1.5000000 3.0000000 3.0000000
[7,]  Inf         Inf        Inf
[8,]  2.1428571 0.8571429 1.2857143
[9,]  Inf         Inf         Inf
[10,] 12.0000000 9.0000000 12.0000000
[11,] 1.6666667 1.6666667 0.6666667
[12,] 1.2857143 1.7142857 0.4285714
[13,] 6.0000000 9.0000000 6.0000000
[14,] 0.6666667 1.6666667 0.6666667
[15,] 2.2500000 3.7500000 2.2500000
[16,] 2.1428571 1.2857143 0.8571429
[17,] 1.7142857 0.4285714 1.2857143
[18,] 0.2500000 1.2500000 0.7500000
[19,] 6.0000000 3.0000000 3.0000000
[20,] 0.2500000 1.2500000 0.7500000
[21,] 12.0000000 9.0000000 12.0000000
[22,] 0.7500000 0.2500000 1.2500000
[23,] 4.0000000 3.0000000 5.0000000
[24,] 0.3333333 0.3333333 1.3333333
[25,] 6.0000000 9.0000000 6.0000000
raja
Published on 10-Aug-2021 08:46:26
Advertisements