How to divide the data.table object rows by row standard deviation in R?


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

Create the data.table object

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

> library(data.table)
> x<-sample(1:100,25)
> y<-sample(1:100,25)
> 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:   45 18
2:    3 99
3:   74 96
4:   67 58
5:   82 24
6:   26 56
7:   93  9
8:   18 22
9:   54 77
10:  96 91
11:  44 30
12:  75  7
13: 100 15
14: 47  25
15: 33  48
16: 37  94
17: 85  73
18: 53 100
19: 66  80
20: 57  89
21: 56  87
22: 11  54
23: 61  26
24: 68   1
25: 38  45
x y

Divide the data.table row values by row standard deviation

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

> library(data.table)
> x<-sample(1:100,25)
> y<-sample(1:100,25)
> DT<-data.table(x,y)
> DT_new<-t(apply(DT,1, function(x) x/sd(x)))
> DT_new

Output

            x       y
[1,]   2.35702260  0.94280904
[2,]   0.04419417  1.45840774
[3,]   4.75690016  6.17111373
[4,]  10.52803430  9.11382074
[5,]   1.99940538  0.58519182
[6,]   1.22565175  2.63986532
[7,]   1.56573644  0.15152288
[8,]   6.36396103  7.77817459
[9,]   3.32032749  4.73454106
[10,] 27.15290040 25.73868684
[11,] 4.44467120   3.03045763
[12,] 1.55979437   0.14558081
[13,] 1.66378066   0.24956710
[14,] 3.02127443   1.60706087
[15,] 3.11126984   4.52548340
[16,] 0.91799828   2.33221184
[17,] 10.01734607  8.60313250
[18,] 1.59475146   3.00896503
[19,] 6.66700679   8.08122036
[20,] 2.51906791   3.93328147
[21,] 2.55470837   3.96892193
[22,] 0.36177556   1.77598912
[23,] 2.46477221   1.05055865
[24,] 1.43532123   0.02110767
[25,] 7.67715934   9.09137290

Updated on: 13-Aug-2021

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements