To calculate the Z-score in R, you can use scale() function or calculate manually using mean() and sd() function.

The following methods show how you can do it with syntax.

Method 1: Use scale() Function

scale(data)

Method 2: Use mean() and sd() Function

(data - mean(data))/sd(data)

The following examples show how to calculate Z-score in R.

Use scale() Function

Let see how we can calculate Z-score for one of the column of dataframe using scale() function:

# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","E","F","G","H"),
                 Pressure=c(78.2, 88.2, 71.7, 80.21, 84.21, 82.56, 72.12, 73.85),
                 Temperature=c(35, 36, 37, 38, 32, 30, 31, 34))

# Find z-score for 'Pressure' column
z_score <- scale(df$Pressure)

# Print Z-score
print(z_score)

Output:

           [,1]
[1,] -0.1131838
[2,]  1.5482304
[3,] -1.1931031
[4,]  0.2207604
[5,]  0.8853261
[6,]  0.6111927
[7,] -1.1233237
[8,] -0.8358990
attr(,"scaled:center")
[1] 78.88125
attr(,"scaled:scale")
[1] 6.018969

The output shows z-score of Pressure column of dataframe.

Use mean() and sd() Function

You can use mean() and sd() function to calculate Z-scores in R:

# Create data frame
df <- data.frame(Pressure=c(78.2, 88.2, 71.7, 80.21, 84.21, 82.56, 72.12, 73.85),
                 Temperature=c(35, 36, 37, 38, 32, 30, 31, 34))

# Find z-score for each column of dataframe
z_score <- (df$Pressure-mean(df$Pressure))/sd(df$Pressure)

# Print Z-score
print(z_score)
[1] -0.1131838  1.5482304 -1.1931031  0.2207604  0.8853261  0.6111927 -1.1233237 -0.8358990

Here the output shows Z-score for Pressure column of dataframe which calculated using mean() and sd() function.