R Tutorial R Charts & Graphs R Statistics R References

R - scale() Function



The R scale() function which centers and scales the columns of a numeric matrix.

The value of center determines how column centering is performed. If center is a numeric-alike vector with length equal to the number of columns of x, then each column of x has the corresponding value from center subtracted from it. If center is TRUE then centering is done by subtracting the column means (omitting NAs) of x from their corresponding columns, and if center is FALSE, no centering is done.

The value of scale determines how column scaling is performed (after centering). If scale is a numeric-alike vector with length equal to the number of columns of x, then each column of x is divided by the corresponding value from scale. If scale is TRUE then scaling is done by dividing the (centered) columns of x by their standard deviations if center is TRUE, and the root mean square otherwise. If scale is FALSE, no scaling is done.

Syntax

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

Parameters

x Required. Specify a numeric matrix(like object).
center Optional. Specify either a logical value or numeric-alike vector of length equal to the number of columns of x.
scale Optional. Specify either a logical value or a numeric-alike vector of length equal to the number of columns of x.

Return Value

Returns the centered, scaled matrix.

Example:

The example below shows the usage of scale() function.

mat <- matrix(1:9, nrow=3)

cat("The matrix contains:\n")
print(mat)

#scale matrix with default arguments
cat("\nscale matrix with default arguments:\n")
print(scale(mat))

The output of the above code will be:

The matrix contains:
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

scale matrix with default arguments:
     [,1] [,2] [,3]
[1,]   -1   -1   -1
[2,]    0    0    0
[3,]    1    1    1
attr(,"scaled:center")
[1] 2 5 8
attr(,"scaled:scale")
[1] 1 1 1

Example:

Consider one more example where center and scale parameters are used.

mat <- matrix(1:9, nrow=3)

cat("The matrix contains:\n")
print(mat)

#scale center by vector of values
cat("\nscale center by vector of values:\n")
print(scale(mat, center=c(1, 2, 3), scale=FALSE))

#scale by vector of values
cat("\nscale by vector of values:\n")
print(scale(mat, center=FALSE, scale=c(1, 2, 3)))

The output of the above code will be:

The matrix contains:
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

scale center by vector of values:
     [,1] [,2] [,3]
[1,]    0    2    4
[2,]    1    3    5
[3,]    2    4    6
attr(,"scaled:center")
[1] 1 2 3

scale by vector of values:
     [,1] [,2]     [,3]
[1,]    1  2.0 2.333333
[2,]    2  2.5 2.666667
[3,]    3  3.0 3.000000
attr(,"scaled:scale")
[1] 1 2 3

❮ R Statistical Functions