How to get the center and scale after using the scale function in R
Asked Answered
R

1

8

It seems a silly question, but I have searched on line, but still did not find any sufficient reply.

My question is: suppose we have a matrix M, then we use the scale() function, how can we extract the center and scale of each column by writing a line of code (I know we can see the centers and scales..), but my matrix has lots of columns, it is cumbersome to do it manually.

Any ideas? Many thanks!

Reasoned answered 8/7, 2018 at 5:47 Comment(0)
M
8

you are looking for the attributes function:

 set.seed(1)
 mat = matrix(rnorm(1000),,10) # Suppose you have 10 columns
 s = scale(mat) # scale your data
 attributes(s)#This gives you the means and the standard deviations:
$`dim`
[1] 100  10

$`scaled:center`
 [1]  0.1088873669 -0.0378080766  0.0296735350  0.0516018586 -0.0391342406 -0.0445193567 -0.1995797418
 [8]  0.0002549694  0.0100772648  0.0040650015

$`scaled:scale`
 [1] 0.8981994 0.9578791 1.0342655 0.9916751 1.1696122 0.9661804 1.0808358 1.0973012 1.0883612 1.0548091

These values can also be obtained as:

 colMeans(mat)
 [1]  0.1088873669 -0.0378080766  0.0296735350  0.0516018586 -0.0391342406 -0.0445193567 -0.1995797418
 [8]  0.0002549694  0.0100772648  0.0040650015
 sqrt(diag(var(mat)))
 [1] 0.8981994 0.9578791 1.0342655 0.9916751 1.1696122 0.9661804 1.0808358 1.0973012 1.0883612 1.0548091

you get a list that you can subset the way you want:

or you can do

attr(s,"scaled:center")
 [1]  0.1088873669 -0.0378080766  0.0296735350  0.0516018586 -0.0391342406 -0.0445193567 -0.1995797418
 [8]  0.0002549694  0.0100772648  0.0040650015

attr(s,"scaled:scale")
 [1] 0.8981994 0.9578791 1.0342655 0.9916751 1.1696122 0.9661804 1.0808358 1.0973012 1.0883612 1.0548091
Mascara answered 8/7, 2018 at 5:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.