R语言 对矩阵的列进行缩放 – scale()函数
R语言中的 scale() 函数是一个通用函数,用于对数字矩阵的列进行定心和缩放。中心参数可以是数字向量或逻辑值。如果提供的是数字向量,那么矩阵的每一列都要从中心减去相应的值。如果提供的逻辑值是TRUE,那么矩阵的列平均值将从其相应的列中减去。刻度可以是数字类向量或逻辑值。如果提供的是数字类向量,那么矩阵的每一列都会被scale中的相应值除以。如果在scale参数中提供了逻辑值,那么矩阵的居中列被除以它们的标准差,否则就是均方根。如果是FALSE,则不对矩阵进行缩放处理。
语法:
scale(x, center = TRUE, scale = TRUE)
参数:
x: 代表数字矩阵
center: 代表逻辑值或等于 x 的数字向量
scale: 代表逻辑值或等于 x 的数字向量
例1:
# Create matrix
mt <- matrix(1:10, ncol = 5)
# Print matrix
cat("Matrix:\n")
print(mt)
# Scale matrix with default arguments
cat("\nAfter scaling:\n")
scale(mt)
输出。
Matrix:
[, 1] [, 2] [, 3] [, 4] [, 5]
[1, ] 1 3 5 7 9
[2, ] 2 4 6 8 10
After scaling:
[, 1] [, 2] [, 3] [, 4] [, 5]
[1, ] -0.7071068 -0.7071068 -0.7071068 -0.7071068 -0.7071068
[2, ] 0.7071068 0.7071068 0.7071068 0.7071068 0.7071068
attr(, "scaled:center")
[1] 1.5 3.5 5.5 7.5 9.5
attr(, "scaled:scale")
[1] 0.7071068 0.7071068 0.7071068 0.7071068 0.7071068
例2:
# Create matrix
mt <- matrix(1:10, ncol = 2)
# Print matrix
cat("Matrix:\n")
print(mt)
# Scale center by vector of values
cat("\nScale center by vector of values:\n")
scale(mt, center = c(1, 2), scale = FALSE)
# Scale by vector of values
cat("\nScale by vector of values:\n")
scale(mt, center = FALSE, scale = c(1, 2))
输出。
Matrix:
[, 1] [, 2]
[1, ] 1 6
[2, ] 2 7
[3, ] 3 8
[4, ] 4 9
[5, ] 5 10
Scale center by vector of values:
[, 1] [, 2]
[1, ] 0 4
[2, ] 1 5
[3, ] 2 6
[4, ] 3 7
[5, ] 4 8
attr(, "scaled:center")
[1] 1 2
Scale by vector of values:
[, 1] [, 2]
[1, ] 1 3.0
[2, ] 2 3.5
[3, ] 3 4.0
[4, ] 4 4.5
[5, ] 5 5.0
attr(, "scaled:scale")
[1] 1 2