两个相同维度矩阵之间的Spearman相关性

3

我有两个相同维度的矩阵(p 和 e),我想要计算同名列之间的Spearman相关性。我希望把配对相关性的输出存在一个矩阵(M)里。

我使用了Psych库中的corr.test()函数,以下是我的操作:

library(psych)
M <- data.frame(matrix(ncol=3,nrow=ncol(p)))
M[,1] <- as.character()
G <- colnames(p)
for(rs in 1:ncol(p){
      M[rs,1] <- G[rs]     
      cor <- corr.test(p[,rs],e[,rs],method="spearman",adjust="none")
      M[rs,2] <- cor$r
      M[rs,3] <- cor$p
}

但是我收到了一个错误信息:
Error in 1:ncol(y) : argument of length 0

请问您能否告诉我哪里出了问题?或者提供另一种方法?


@thelatemail提供了正确的解决方案;但在你的代码中,可以通过将corr.test行更改为corr.test(as.data.frame(p[,rs]), as.data.frame(e[,rs]), method="spearman", adjust="none")来实现。从错误消息中可以得到的提示是,该函数期望x/y参数具有二维数据结构。 - undefined
@DominicComtois 谢谢,问题已解决! - undefined
2个回答

7
不需要进行循环和索引等操作:
# test data
p <- matrix(data = rnorm(100),nrow = 10)
e <- matrix(data = rnorm(100),nrow = 10)

cor <- corr.test(p, e, method="spearman", adjust="none")
data.frame(name=colnames(p), r=diag(cor$r), p=diag(cor$p))

#  name           r         p
#a    a  0.36969697 0.2930501
#b    b  0.16363636 0.6514773
#c    c -0.15151515 0.6760652
# etc etc

如果矩阵的名称尚未匹配,则请将它们匹配
cor <- corr.test(p, e[,match(colnames(p),colnames(e))], method="spearman", adjust="none")

0
由于这两个矩阵非常庞大,使用system.time来执行函数corr.test()对所有可能的配对进行计算将会非常耗时,但最终成功的循环如下所示:
    library(psych)
    M <- data.frame(matrix(ncol=3,nrow=ncol(p)))
    M[,1] <- as.character()
    G <- colnames(p)
    for(rs in 1:ncol(p){
          M[rs,1] <- G[rs]     
          cor <- corr.test(as.data.frame(p[,rs]),as.data.frame(e[,rs]),
method="spearman",adjust="none")
          M[rs,2] <- cor$r
          M[rs,3] <- cor$p
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接