How to convert a variable into zero mean and unit variance in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

Converting a variable into zero mean and unit variance means that we want to standardize the variable and it can be done with the help of scale function we can follow the below steps −

• First of all, creating data frame.
• Then using scale function to convert the variable into zero mean and unit variance.

Create the data frame

Let's create a data frame as shown below −

Live Demo

x<-sample(1:100,20)
df<-data.frame(x)
df

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

   x
1  87
2  17
3  28
4  100
5  41
6  44
7  25
8  92
9  37
10 3
11 9
12 46
13 15
14 53
15 29
16 65
17 99
18 91
19 83
20 51

Converting variable zero mean and unit variance

Use scale function to convert x into zero mean and unit variance variable −

Live Demo

x<-sample(1:100,20)
df<-data.frame(x)
Converted_df<-scale(df\$x)
Converted_df

Output

           [,1]
[1,]   1.143807532
[2,]  -1.064924254
[3,]  -0.717837830
[4,]   1.554000578
[5,]  -0.307644784
[6,]  -0.212984851
[7,] -0.812497764
[8,]   1.301574088
[9,] -0.433858029
[10,] -1.506670611
[11,] -1.317350744
[12,] -0.149878228
[13,] -1.128030876
[14,] 0.070994950
[15,] -0.686284519
[16,] 0.449634685
[17,] 1.522447267
[18,] 1.270020777
[19,] 1.017594287
[20,] 0.007888328
attr(,"scaled:center")
[1] 50.75
attr(,"scaled:scale")
[1] 31.69239
Updated on 13-Aug-2021 11:48:31