【问题标题】:Is there any function that calculate correlation between a set of matrices included in an array in R?是否有任何函数可以计算 R 中数组中包含的一组矩阵之间的相关性?
【发布时间】:2019-11-23 01:36:37
【问题描述】:

我有一个包含 20 个矩阵的列表。我想计算所有矩阵之间的皮尔逊相关性。但我找不到任何可能的代码或功能?您能否提供一些建议。

something like:
a=matrix(1:8100, ncol = 90)
b=matrix(8100:16199, ncol = 90)
c=matrix(sample(16200:24299),ncol = 90)
z=list(a,b,c)

我发现: https://rdrr.io/cran/lineup/man/corbetw2mat.html 试试看:

library(lineup)
corbetw2mat(z[a], z[b], what = "all")

我遇到以下错误:

Error in corbetw2mat(z[a], z[b], what = "all") : 
  (list) object cannot be coerced to type 'double'

我想要一个这样的列表作为结果:

a & b 
correlations
a & c
correlations
b & c
correlations

谢谢

【问题讨论】:

  • 欢迎来到stackoverflow!您的问题不清楚,请根据How to make a great R reproducible example阅读并编辑您的问题,以便其他用户可以帮助您。另外,添加预期的输出。
  • 您还没有真正解释您期望的答案是什么。如果您发布了一个代码块,该代码块创建了一个较小的数字,您可以手动给出“正确”的答案,那最好。

标签: arrays r correlation


【解决方案1】:

我将创建一个较小的数据集来说明下面的解决方案。
要获得成对组合,最好的选择是使用combn 计算组合矩阵,然后循环遍历它,在本例中为lapply 循环。

set.seed(1234)    # Make the results reproducible

a <- matrix(1:9, ncol = 3)
b <- matrix(rnorm(9), ncol = 3)
c <- matrix(sample(1:9), ncol = 3)
sample_list <- list(a, b, c)

cmb <- combn(3, 2)
res <- lapply(seq.int(ncol(cmb)), function(i) {
  cor(sample_list[[ cmb[1, i] ]], sample_list[[ cmb[2, i] ]])
})

结果在列表res 中。

注意sample是一个base r函数,所以我把名字改成了sample_list

【讨论】:

  • 非常感谢。抱歉问这个问题,我看不懂 cmb 部分;对于包含 20 个矩阵的真实数据,我应该使用什么组合,更重要的是为什么?
  • @Baghererfanian 来自帮助页面?combn一次生成 x 的元素的所有组合 m。 所以如果你有 20 个矩阵,你会得到对(1,2),然后是 (1,3),等等,直到 (1,20),然后是 (2,3) 等等。将答案中的呼叫替换为 cmb &lt;- combn(20, 2)
  • @Baghererfanian 当someone answers你的问题时该怎么办。
猜你喜欢
  • 1970-01-01
  • 2019-08-30
  • 2013-03-15
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多