【问题标题】:How can I calculate the correlation coefficients on the third dimension of an array?如何计算数组第三维的相关系数?
【发布时间】:2016-08-16 08:03:29
【问题描述】:

比如说,我有一个三维数组,其中项目为行,项目为列,参与者为第三维,同时出现计数中的值。 进一步注意,每个数组“切片”(= 项 x 项矩阵)都是对称的(因为它们是共现计数!)。

像这样:

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() 操作来实现这一点,如下所示,但我猜 必须有一种更有效的矩阵魔法方式来做这个,对吧?


这是我现在做这个的hacky方式。别笑。

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

【问题讨论】:

  • 等一下,你对我来说太快了:)

标签: arrays r matrix correlation


【解决方案1】:

怎么样

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

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

【讨论】:

  • 谢谢;这肯定看起来要快得多。我仍然想知道是否可能有 matrix 代数方式来做到这一点,正如(也许?)描述的here。这似乎是通过差分矩阵,然后是协方差矩阵(现在可以)。你知道这是否会仍然更快?非常感谢代码,我会自己在这里添加基准。
猜你喜欢
  • 1970-01-01
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-15
  • 2018-09-10
  • 1970-01-01
相关资源
最近更新 更多