📜  在 R 编程中缩放矩阵的列 – scale()函数

📅  最后修改于: 2022-05-13 01:54:36.232000             🧑  作者: Mango

在 R 编程中缩放矩阵的列 – scale()函数

R 语言中的scale()函数是一个通用函数,它使数字矩阵的列居中和缩放。 center参数采用类似数字的向量或逻辑值。如果提供了数字向量,则矩阵的每一列都会从center减去相应的值。如果提供的逻辑值为 TRUE,则从其对应的列中减去矩阵的列均值。 scale采用数字相似向量或逻辑值。当提供类似数字的向量时,矩阵的每一列都除以来自scale的相应值。如果在scale参数中提供了逻辑值,则矩阵的居中列除以它们的标准差,否则为均方根。如果为 FALSE,则不对矩阵进行缩放。

示例 1:

r
# 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)


r
# 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] [, 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:

r

# 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