 # Manually computing correlation coefficient

Hi, I am new to programming with R but I have an assignment to manually code the correlation coefficient between two variables , X and Y, from a dataset. Both variables have 400 observations. I have been unsuccessful in properly computing the code thus far, this is what I have:

for(i in 1:n){
n = length(X)
Xbar = mean(X)
Ybar = mean(Y)
Xstat = X[i]-Xbar
Ystat = Y[i]-Ybar
r = (sum(Xstat * Ystat))/(sqrt((sum(Xstat^2))*(sum(Ystat^2))))
r
}

Any help would be great!

Notice that when the for loop starts there is no value for n. It should be computed before the loop. Also, Xbar and Ybar are constant, so they can be computed before the loop.

Think more carefully about the order of commands in a loop. For example your for statement has n in it, but n isn't defined yet. And you are summing Xstat^2 before you've put in all the values of Xstat.

I have an assignment to manually code the correlation coefficient between two variables , X and Y

Why? What is wrong with

``````cor(X, Y)
``````

?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.