1

我有两个相同维度的矩阵(p 和 e),我想在同名的列之间建立一个 spearman 相关性。我想在矩阵(M)中输出对相关性

我使用了corr.test()Psych 库中的函数,这就是我所做的:

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

你能告诉我有什么问题吗?或建议另一种方法?

4

2 回答 2

5

不需要所有这些循环和索引等:

# 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

如果矩阵的名称不匹配,则match它们:

cor <- corr.test(p, e[,match(colnames(p),colnames(e))], method="spearman", adjust="none")
于 2015-03-16T04:24:05.467 回答
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
    }
于 2015-03-16T18:04:12.583 回答