【问题标题】:compute array of correlations between two multidimensional arrays in R计算R中两个多维数组之间的相关数组
【发布时间】:2018-08-05 09:32:11
【问题描述】:

我有两个三维数组 X[nx, ny, nt] 和 Y[n​​x, ny, nt]。我想计算一个相关矩阵 R,使得 Rij = cor(Xij, Yij)。

我可以通过嵌套的 for 循环来做到这一点:

for (i in 1:nx) {
  for (j in 1:ny) {
    R[i,j] <- cor(X[i,j,], Y[i,j,], use='complete.obs')
  }
}

有没有更好的方法使用 apply 的一些变体?

【问题讨论】:

  • R &lt;- sapply(1:nx, function(i,j) cor(X[i,j,], Y[i,j,], use='complete.obs'), 1:ny)?
  • 如果你担心速度,cor函数比使用for慢得多
  • @Parfait 该结果的维度为 [nt*nt, nx]。
  • @Gilgamesh 你是对的。我原来的 for 循环比下面的 apply with abind 快。

标签: arrays r apply


【解决方案1】:

使用abind,我们可以将这两个数组组合成一个四维数组,然后在前两个维度上使用apply

library(abind)
apply(abind(X, Y, along = 4), 1:2, function(Z) cor(Z[, 1], Z[, 2]))

【讨论】:

    猜你喜欢
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    相关资源
    最近更新 更多