Scale the Columns of a Matrix in R Programming scale() Function (original) (raw)

Last Updated : 17 Apr, 2025

The s cale() function in R is used to center and/or scale the columns of a numeric matrix. It helps standardize data by transforming it to have a mean of 0 and standard deviation of 1 .

**Syntax

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

**Parameters:

**Example 1:

In this example, a 2x5 matrix is created and then standardized using the scale() function, which centers each column by subtracting its mean and scales it by dividing by its standard deviation.

R `

mt <- matrix(1:10, ncol = 5)

cat("Matrix:\n") head(mt)

Scale matrix with default arguments

cat("\nAfter scaling:\n") scale(mt)

`

**Output:

Scale-funtion-on-2x5

Scaling a 2x5 matrix

**Example 2:

In this example, a 5x4 matrix is created and then the scale() function is used in two ways: first to center the matrix by subtracting a specified vector of values from each column and second to scale the matrix by dividing each column by a specified vector of values.

R `

mt <- matrix(1:20, ncol = 4) head(mt)

Scale center by vector of values

cat("\nScale center by vector of values:\n") scale(mt, center = c(1, 2, 3, 4), scale = FALSE)

Scale by vector of values

cat("\nScale by vector of values:\n") scale(mt, center = FALSE, scale = c(1, 2, 3, 4))

`

**Output:

scale-on-5x4

Scaling a 5x4 matrix