In R, there seems to be a discrepancy for calculating the pearson correlation coefficient, between (a) using the raw-score formula in one step and (b) evaluating the numerator and denominator separately first. In particular, when I did the calculation in one step, the result was erroneous, but it was correct when I evaluated the numerator and denominator separately first. How come? I might be doing something wrong, but I can't figure out what it is.
##data
x <- 1:5
y <- 5:1
##x squared, y squared, x times y; for raw score formula
xx <- x*x
yy <- y*y
xy <- x*y
##correlation coefficient; the value that should come out
cor(x,y) #-1
##raw score formula, in one line
wrong <- length(xy)*sum(xy)-sum(x)*sum(y)/
sqrt((length(xx)*sum(xx)-sum(x)^2)*(length(yy)*sum(yy)-sum(y)^2))
wrong #170.5
##raw score formula, separating numerator and denominator
numerator <- length(xy)*sum(xy)-sum(x)*sum(y)
denominator <- sqrt((length(x)*sum(xx)-sum(x)^2)*(length(y)*sum(yy)-sum(y)^2))
correct <- numerator/denominator
correct #-1
I'm using R 2.14.1 in Xubuntu 12.04.