如何计算数组第三维的相关系数?

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

比如说,我有一个三维数组,项目作为行,项目作为列,参与者作为第三维,值在共同出现计数中。 进一步注意每个数组 "slices"(= 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

您可以将上面的代码压缩成一行。但是为了便于阅读演示,我采用了循序渐进的方法。