![](/img/trans.png)
[英]Calculate the correlation of coefficient if the variables are time series in r
[英]Correlation coefficient for three variables in r
對於三個n維非零方差變量a,b和c,n> 2,如果r(ab),r(bc)和r(ac)是a和b之間,b和b之間的皮爾遜相關系數。 c以及分別在a和c之間,則a,b和c之間的相關系數r(abc)定義為:
r ^ 2(abc)=(r ^ 2(ab)+ r ^ 2(bc)+ r ^ 2(ac))-(2 xr(ab)xr(bc)xr(ac))
我能夠以手動方式獲取代碼:
a <- c(4, 6, 2, 7)
b <- c(8, 1, 3, 5)
c <- c(6, 3, 1, 9)
al <- data.frame(a, b, c)
al
ab_cor <- cor(al$a, al$b, method = c("pearson"))
bc_cor <- cor(al$b, al$c, method = c("pearson"))
ac_cor <- cor(al$a, al$c, method = c("pearson"))
abc_cor <- sqrt( ( (ab_cor)^2 + (bc_cor)^2 + (ac_cor)^2 ) - ( 2 * ab_cor * bc_cor * ac_cor) )
abc_cor
但是我想知道是否可以用更少的代碼行來完成,例如使用for循環。 另外,我將如何編寫它以便也可以使用3個以上的變量來完成它,例如r(abcd)即r(ab),r(ac),r(ad),r(bc),r (bd)和r(cd)。
cor函數已經創建了相關矩陣。 您只需要選擇相關的內容,然后使用一些向量運算即可。
cs <- cor(al, method = "pearson")
cs <- cs[upper.tri(cs)]
#sqrt(sum(cs^2)) - 2*prod(cs)
# apparently it's
sqrt(sum(cs^2) - 2*prod(cs))
假設您在al
data.frame中擁有所有想要的變量,這也會推廣到較大的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.