R: Standardize using mean and sd functions

限于喜欢 提交于 2019-12-25 02:19:34

问题


I'm trying to do a simple transformation. I've used the following code and it worked fine:

data_stdz <- transform(data_header, z.v1 = v1+2)

But, I can't get the following code to work:

data_stdz <- transform(data_header, z.v1 = (v1 - mean(v1))/(2*sd(v1))

I've also tried to get just the mean function to work:

data_stdz <- transform(data_header, z.v1 = mean(v1)

But, I keep getting the following error:

Error: unexpected symbol in:
"data_std2 <- transform(data_header, z.v1 = mean(v1)
data_std2"

So I'm guessing it has something to do with how I am using the mean and sd function, but I have not been able to figure it out.

Data example:

v1   v2  v3
6.7 3.8 1.2
6.3 3.2 1.2
6.1 2.6 1.6
7   2.4 1
NA  NA  NA
6.5 3.6 2.6
6.1 2.4 1.6
6   5.6 5.2
7   2.8 1
6.7 3.8 1.4
5.7 4.2 2.6
5.1 5.6 5
NA  NA  NA

回答1:


Your problem is likely (in additon to what gavin said) the NAs. Use na.rm=TRUE as in:

transform(data_header, z.v1 = (v1 - mean(v1, na.rm =T))/(2*sd(v1, na.rm =T)))



回答2:


Base R has the scale() function for this purpose.



来源:https://stackoverflow.com/questions/9649821/r-standardize-using-mean-and-sd-functions

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