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


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

Create the data frame

library(data.table)
x<-sample(1:50,25)
y<-sample(1:50,25)
z<-sample(1:50,25)
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:  26 34 16
2:  2  23 40
3:  23 9  37
4:  24 14 22
5:  4  20 33
6:  35 38 47
7:  21 3  10
8:  34 41 13
9:  42 33 35
10: 15 7  4
11: 18 1  23
12: 45 4  49
13: 11 8  19
14: 50 49  5
15: 13 39  9
16: 12 21 46
17: 20 29 42
18: 28 32 38
19: 25 47 32
20: 32 22 20
21: 46 45 43
22: 6 15  31
23: 22 48 29
24: 30 5  17
25: 27 46 44
    x  y  z

Divide the data.table object row values by row mean

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

library(data.table)
x<-sample(1:50,25)
y<-sample(1:50,25)
z<-sample(1:50,25)
DT<-data.table(x,y,z)
DT_new<-t(apply(DT,1, function(x) x/mean(x)))
DT_new

Output

         x          y          z
[1,] 1.02631579 1.34210526 0.6315789
[2,] 0.09230769 1.06153846 1.8461538
[3,] 1.00000000 0.39130435 1.6086957
[4,] 1.20000000 0.70000000 1.1000000
[5,] 0.21052632 1.05263158 1.7368421
[6,] 0.87500000 0.95000000 1.1750000
[7,] 1.85294118 0.26470588 0.8823529
[8,] 1.15909091 1.39772727 0.4431818
[9,] 1.14545455 0.90000000 0.9545455
[10,] 1.73076923 0.80769231 0.4615385
[11,] 1.28571429 0.07142857 1.6428571
[12,] 1.37755102 0.12244898 1.5000000
[13,] 0.86842105 0.63157895 1.5000000
[14,] 1.44230769 1.41346154 0.1442308
[15,] 0.63934426 1.91803279 0.4426230
[16,] 0.45569620 0.79746835 1.7468354
[17,] 0.65934066 0.95604396 1.3846154
[18,] 0.85714286 0.97959184 1.1632653
[19,] 0.72115385 1.35576923 0.9230769
[20,] 1.29729730 0.89189189 0.8108108
[21,] 1.02985075 1.00746269 0.9626866
[22,] 0.34615385 0.86538462 1.7884615
[23,] 0.66666667 1.45454545 0.8787879
[24,] 1.73076923 0.28846154 0.9807692
[25,] 0.69230769 1.17948718 1.1282051

Updated on: 13-Aug-2021

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements