这个功能都包含在基础 R 中。假设我们有一个数字矩阵/data.frame:
tst <- matrix(rnorm(n <- 30, 5), nrow = n/3)
tst
#> [,1] [,2] [,3]
#> [1,] 4.829019 5.512795 5.079292
#> [2,] 5.936711 5.609443 5.365723
#> [3,] 5.532721 5.933239 5.419975
#> [4,] 4.857640 3.771058 6.097233
#> [5,] 4.616931 6.160274 3.499183
#> [6,] 4.639770 6.391719 2.508426
#> [7,] 6.710327 4.295331 5.860477
#> [8,] 4.110706 5.283023 5.222424
#> [9,] 5.422139 4.204371 5.724206
#> [10,] 4.413287 6.060544 5.768139
现在缩放该对象:
tst_scaled <- scale(tst)
tst_scaled
#> [,1] [,2] [,3]
#> [1,] -0.3519527 0.20749667 0.02159387
#> [2,] 1.0508778 0.31270353 0.27115886
#> [3,] 0.5392462 0.66517525 0.31842816
#> [4,] -0.3157060 -1.68848936 0.90851618
#> [5,] -0.6205499 0.91231582 -1.35513839
#> [6,] -0.5916256 1.16425789 -2.21837548
#> [7,] 2.0306182 -1.11778652 0.70223277
#> [8,] -1.2616555 -0.04262486 0.14630372
#> [9,] 0.3992004 -1.21680202 0.58350100
#> [10,] -0.8784529 0.80375360 0.62177933
#> attr(,"scaled:center")
#> [1] 5.106925 5.322180 5.054508
#> attr(,"scaled:scale")
#> [1] 0.7896126 0.9186446 1.1477238
反之,取消缩放该对象:
tst_unscaled <- tst_scaled %*%
diag(attr(tst_scaled, "scaled:scale")) +
matrix(
rep(attr(tst_scaled, "scaled:center"), nrow(tst_scaled)),
ncol = ncol(tst_scaled),
byrow = TRUE
)
tst_unscaled
#> [,1] [,2] [,3]
#> [1,] 4.829019 5.512795 5.079292
#> [2,] 5.936711 5.609443 5.365723
#> [3,] 5.532721 5.933239 5.419975
#> [4,] 4.857640 3.771058 6.097233
#> [5,] 4.616931 6.160274 3.499183
#> [6,] 4.639770 6.391719 2.508426
#> [7,] 6.710327 4.295331 5.860477
#> [8,] 4.110706 5.283023 5.222424
#> [9,] 5.422139 4.204371 5.724206
#> [10,] 4.413287 6.060544 5.768139
确认我们的原始对象和未缩放对象是相同的:
identical(tst_unscaled, tst)
#> [1] TRUE