Question

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
Was it helpful?

Solution

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)))

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top