Horseman1901
Horseman1901

Reputation: 13

how to calculate the Correlation coefficient using R using a function?

Hello! I'm trying to write a function deriving the formula for Pearson's coefficient of correlation . I wrote the following code but when I try to pass the values, it returns empty output. Please point me to my error, I'm clueless! Much appreciated.

correlation = function(X, Y, n = length(X)){
sum_X = 0
sum_Y = 0
sum_XY = 0
squareSum_X = 0
squareSum_Y = 0
i = 0
while (i < n ) { 
    # sum of elements of array X. 
    sum_X = sum_X + X[i] 

    # sum of elements of array Y. 
    sum_Y = sum_Y + Y[i] 

    # sum of X[i] * Y[i]. 
    sum_XY = sum_XY + X[i] * Y[i] 

    # sum of square of array elements. 
    squareSum_X = squareSum_X + X[i] * X[i] 
    squareSum_Y = squareSum_Y + Y[i] * Y[i] 

    i =+ 1
}
# combine all into a final formula
final = (n * sum_XY - (sum_X * sum_Y))/ (sqrt((n * squareSum_X - sum_X * sum_X)* (n * squareSum_Y - 
sum_Y * sum_Y))) 
return (final)
}

Upvotes: 0

Views: 738

Answers (1)

andrew_reece
andrew_reece

Reputation: 21284

R is a 1-indexed language. Start with i = 1 and change to while(i <= n) (and fix the iteration counter as noted in the comments: i = i + 1. Then your function works correctly.

n <- 100
x <- rnorm(n)
y <- rnorm(n)

round(correlation(x, y), 4) == round(cor(x, y), 4) # TRUE

Note, however, that R is also great for vectorized operations, and you can skip the explicit loop altogether. Something like this is a step towards getting more efficient:

correlation2 <- function(X, Y){
  n <- length(X)
  sum_X <- sum(X)
  sum_Y <- sum(Y)
  sum_XY <- sum(X * Y)
  squareSum_X <- sum(X * X)
  squareSum_Y <- sum(Y * Y)
  final <- (n * sum_XY - (sum_X * sum_Y)) / (sqrt((n * squareSum_X - sum_X * sum_X)* (n * squareSum_Y - sum_Y * sum_Y))) 
  return (final)
}

round(correlation2(x, y), 4) == round(cor(x, y), 4) # TRUE

Or even just:

correlation3 <- function(X, Y){
  n = length(X)
  sum_x = sum(X)
  sum_y = sum(Y)
  (n * sum(X * Y) - sum_x * sum_y) / 
    (sqrt((n * sum(x^2) - sum_x^2) * (n * sum(Y^2) - sum_y^2)))
}

Upvotes: 1

Related Questions