scale() Function in R

scale() function in R allows us to standardize a vector or matrix. Standardization is the process of scaling a vector or matrix so that it has a mean of 0 and a standard deviation of 1. This is useful for many machine learning algorithms, such as regression and support vector machines, which require that data be normalized.

Syntax

scale(x, center=TRUE, scale=TRUE)

Arguments

  • x = a vector or matrix to be scaled or standardized
  • center = a logical value that tells the function whether to center the data before scaling. The default value is TRUE.
  • scale = a logical value that tells the function whether to scale the data. The default value is TRUE.

Example

Let’s create a vector of data, then standardize it using the scale() function.

#creating a vector
x = c(1,2,3,4,5)
#scaling the vector x
scale(x)

Output

[1,] -1.2649111
[2,] -0.6324555
[3,] 0.0000000
[4,] 0.6324555
[5,] 1.2649111
attr(,"scaled:center")
[1] 3
attr(,"scaled:scale")
[1] 1.581139

The output shows the standardized values of the data. To confirm if the data is standardized or not, calculate the mean and standard deviation of the output:

mean(c(-1.2649111,-0.6324555,0.0000000,0.6324555,1.2649111))
sd(c(-1.2649111,-0.6324555,0.0000000,0.6324555,1.2649111))

Output

[1] 0
[1] 1

As we can see, the mean of the data is 0, and the standard deviation is 1.

Leave a Comment