当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 scale()用法及代码示例


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

用法:
scale(x, center = TRUE, scale = TRUE)

参数:
x:表示数字矩阵
center:表示等于 xscale 数量的逻辑值或数值相似向量:表示等于 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



相关用法


注:本文由纯净天空筛选整理自utkarsh_kumar大神的英文原创作品 Scale the Columns of a Matrix in R Programming – scale() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。