簡體   English   中英

如何使用函數使用R計算相關系數?

[英]how to calculate the Correlation coefficient using R using a function?

你好! 我正在嘗試編寫一個函數來推導出 Pearson 相關系數的公式。 我編寫了以下代碼,但是當我嘗試傳遞值時,它返回空輸出。 請指出我的錯誤,我一無所知! 非常感激。

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

R 是 1 索引語言。 i = 1開始並更改為while(i <= n) (並按照注釋中的說明修復迭代計數器: i = i + 1 。然后您的函數可以正常工作。

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

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

但是請注意,R 也非常適合矢量化操作,您可以完全跳過顯式循環。 像這樣的事情是提高效率的一步:

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

或者甚至只是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM