當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。