簡體   English   中英

如何在數組的第三維上計算相關系數?

[英]How can I calculate the correlation coefficients on the third dimension of an array?

說,我有一個三維數組,其中項目作為行,項目作為列,參與者作為第三維,共現計數值。 還要注意,每個數組“切片”(= item x item矩陣)都是對稱的(因為它們是共存計數!)。

像這樣:

a <- structure(c(17L, 1L, 0L, 1L, 1L, 17L, 0L, 1L, 0L, 0L, 17L, 0L, 1L, 1L, 0L, 17L, 16L, 0L, 0L, 1L, 0L, 16L, 0L, 0L, 0L, 0L, 16L, 0L, 1L, 0L, 0L, 16L, 18L, 1L, 2L, 3L, 1L, 18L, 1L, 2L, 2L, 1L, 18L, 0L, 3L, 2L, 0L, 18L), .Dim = c(4L, 4L, 3L), .Dimnames = structure(list(items = c("but-how", "encyclopedia", "alien", "comma"), items = c("but-how", "encyclopedia", "alien", "comma"), people = c("Julius", "Tashina", "Azra")), .Names = c("items", "items", "people")))

我現在想要參與者x參與者的相關系數矩陣,即JuliusTashinaAzra的相應系數。 為此,我只想關聯兩個矩陣中它們各自的單元,因此對於AzraTashina ,我要關聯它們各自的上(或下)三角形。

對我而言,如何執行此操作並不明顯,因為cor()和朋友不接受數組。

我可以通過下面的一些apply()upper.tri()動作來破解它,但是我猜想必須有一種更有效,矩陣神奇的方式來做到這一點,對嗎?


這是我現在執行此操作的方式。 不要笑

loosedat <- apply(X = a, MARGIN = c(3), FUN = function(x) {
    x <- x[upper.tri(x = x, diag = FALSE)]  # must kill diagonal, will otherwise inflate results
})  
cor(loosedat)

讓我得到我想要的東西,但是我覺得這很骯臟。

           Julius   Tashina     Azra
Julius  1.0000000 0.4472136 0.522233
Tashina 0.4472136 1.0000000 0.700649
Azra    0.5222330 0.7006490 1.000000

怎么樣

n <- dim(a)[3L]    ## number of people
m <- dim(a)[1L]    ## square table dimension
id <- dimnames(a)[[3L]]    ## name of people
uptri <- upper.tri(diag(m))    ## upper triangular index
loosedat <- matrix(as.numeric(a)[uptri], ncol = n, dimnames = list(NULL, id))
#     Julius Tashina Azra
#[1,]      1       0    1
#[2,]      0       0    2
#[3,]      0       0    1
#[4,]      1       1    3
#[5,]      1       0    2
#[6,]      0       0    0

cor(loosedat)
#           Julius   Tashina     Azra
#Julius  1.0000000 0.4472136 0.522233
#Tashina 0.4472136 1.0000000 0.700649
#Azra    0.5222330 0.7006490 1.000000

您可以將上面的代碼壓縮為一行。 但是為了便於閱讀,我采用了逐步的方法。

暫無
暫無

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

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