Skip to content
Related Articles

Related Articles

z-score Standardization in R
  • Last Updated : 24 Feb, 2021
GeeksforGeeks - Summer Carnival Banner

In statistics, the task is to standardize variables which are called valvulating z-scores. Comparing two standardizing variables is the function of standardizing vector. By subtracting the vector by its mean and dividing the result by the vector’s standard deviation we can standardize a vector.

Formula:

Z= (x – mean)/standard deviation

Approach:

  • Declare a vector
  • Calculate its mean and standard deviation by the functions mean() and sd().
  • To create a standardized vector:
    • Subtract mean from the vector
    • Now divide the above result with standard deviation

R






a <- c(7, 8, 3, 2, 2, 10, 9)
  
# Finding Mean
m<-mean(a)
  
# Finding Standard Deviation
s<-sd(a)
  
#standardized vector
a.z<-(a-m)/s
  
a.z

Output:

[1]  0.3325644  0.6235582 -0.8314110 -1.1224048 -1.1224048  1.2055459  0.9145521

Now we can also check whether the vector has been correctly standardized or not by checking if its mean is zero and the standard deviation is one. The answer of mean is not coming exactly zero but almost zero. Which is acceptable since it is the result of computer laws.

Program:

R




a <- c(7, 8, 3, 2, 2, 10, 9)
  
# Finding Mean
m<-mean(a)
  
# Finding Standard Deviation
s<-sd(a)
  
#standardized vector
a.z<-(a-m)/s
  
mean(a.z)
  
sd(a.z)

Output:

[1] 1.427197e-16

[1] 1

Example 2: 

R




a <- c(10, 6, 3, 5, 4)
b <- c(150, 200, 500, 600, 850)
  
a.z <- (a - mean(a)) / sd(a)
  
b.z <- (b - mean(b)) / sd(b)
  
average.z <- (a.z + (b.z)) / 2
round(average.z, 1)

Output:

[1]  0.3 -0.4 -0.4  0.1  0.4

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :