How to divide the data frame rows in R by row standard deviation?

R ProgrammingServer Side ProgrammingProgramming

To divide the data frame row values by row standard deviation in R, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use apply function to divide the data frame row values by row standard deviation.

Creating the data frame

Let's create a data frame as shown below −

 Live Demo

> x<-round(rnorm(25),2)
> y<-round(rnorm(25),2)
> df<-data.frame(x,y)
> df

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

      x     y
1   1.48  0.86
2  -0.14 -0.58
3  -0.25  1.22
4   0.18  0.25
5   0.50  0.68
6  -1.34 -0.21
7   0.43 -0.54
8   0.32 -1.00
9   0.09 -0.19
10  1.20 -1.23
11 -1.48  0.73
12 -0.67 -0.19
13 -1.54  0.09
14  0.51  0.16
15 -1.38  0.05
16 -0.33  1.69
17  0.96  0.95
18 -0.70 -1.56
19 -0.53  0.42
20  0.01  0.77
21 -0.99 -1.76
22 -0.06 -0.34
23 -0.91  0.80
24 -1.01 -1.36
25  1.45 -0.35

Dividing the data frame row values by row standard deviation

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

 Live Demo

Using col Means function to find the column means −

> x<-round(rnorm(25),2)
> y<-round(rnorm(25),2)
> df<-data.frame(x,y)
> df_new<-t(apply(df,1, function(x) x/sd(x)))
> df_new

Output

                 x            y
[1,]    3.37586463   1.96165107
[2,]   -0.44997704  -1.86419060
[3,]   -0.24051251   1.17370105
[4,]    3.63654916   5.05076272
[5,]    3.92837101   5.34258457
[6,]   -1.67703201  -0.26281845
[7,]    0.62691941  -0.78729415
[8,]    0.34283965  -1.07137391
[9,]    0.45456865  -0.95964492
[10,]   0.69837707  -0.71583649
[11,]  -0.94707515   0.46713842
[12,]  -1.97400643  -0.55979287
[13,]  -1.33612815   0.07808541
[14,]   2.06071119   0.64649763
[15,]  -1.36476554   0.04944803
[16,]  -0.23103489   1.18317867
[17,]  135.76450199 134.35028843
[18,]  -1.15110406  -2.56531762
[19,]  -0.78898230   0.62523126
[20,]   0.01860807   1.43282164
[21,]  -1.81827458  -3.23248814
[22,]  -0.30304576  -1.71725933
[23,]  -0.75259318   0.66162038
[24,]  -4.08101628 -5.49522984
[25,]   1.13922759 -0.27498597
raja
Published on 14-Jul-2021 07:32:26
Advertisements