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
}
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.