Function that converts a vector of numbers to a vector of standard units

谁说胖子不能爱 提交于 2019-12-03 19:13:03

问题


Is there a function that given a vector of numbers, returns another vector with the standard units corresponding to each value?

where standard unit: how many SDs a value is + or - from the mean

Example:

 x <- c(1,3,4,5,7)    # note: mean = 4, sd = 2
 foo(x) 
 [1]  -1.5  -0.5  0.0  0.5  1.5

Is this fictitious "foo" function already included in a package?


回答1:


yes, scale():

x <- c(1,3,4,5,7)
scale(x)



回答2:


The function you are looking for is scale.

scale(x)


           [,1]
[1,] -1.3416408
[2,] -0.4472136
[3,]  0.0000000
[4,]  0.4472136
[5,]  1.3416408
attr(,"scaled:center")
[1] 4
attr(,"scaled:scale")
[1] 2.236068

Note that the answers are not identical to what you posted in your question. The reason is that the standard deviation in your x is actually 2.23, not 2.

sd(x)
[1] 2.236068



回答3:


How about simply (x-mean(x))/sd(x), or am I missing some subtlety here?



来源:https://stackoverflow.com/questions/5835545/function-that-converts-a-vector-of-numbers-to-a-vector-of-standard-units

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!