How to Compute z-scores in R Programming (Example Code)

In this article, I’ll explain how to calculate z-scores in the R programming language.

Creation of Example Data

data(iris)                            # Load iris flower data
iris_num <- iris[ , 1:4]              # Remove non-numeric columns
head(iris_num)                        # Head of numeric iris data
#   Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1          5.1         3.5          1.4         0.2
# 2          4.9         3.0          1.4         0.2
# 3          4.7         3.2          1.3         0.2
# 4          4.6         3.1          1.5         0.2
# 5          5.0         3.6          1.4         0.2
# 6          5.4         3.9          1.7         0.4

Example: Standardize Variables of Data Frame Using scale() Function

iris_num_scaled <- scale(iris_num)    # Scaling data
head(iris_num_scaled)                 # Head of scaled data
#      Sepal.Length Sepal.Width Petal.Length Petal.Width
# [1,]   -0.8976739  1.01560199    -1.335752   -1.311052
# [2,]   -1.1392005 -0.13153881    -1.335752   -1.311052
# [3,]   -1.3807271  0.32731751    -1.392399   -1.311052
# [4,]   -1.5014904  0.09788935    -1.279104   -1.311052
# [5,]   -1.0184372  1.24503015    -1.335752   -1.311052
# [6,]   -0.5353840  1.93331463    -1.165809   -1.048667

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top