2012-12-28 22 views
2

有没有更好的方法来迭代给定数据集的一组参数?显然,我试图得到一个相关系数表:列是“CI,CVP,平均PAP,平均SAP”,行是“ALAT,ASAT,GGT,Bili,LDH,FBG”。对于每个组合,我想要得到相关系数和显着性水平(p = ...)。 下面你看到“困难的方式”。但是,有没有更优雅的方式,可能有可打印的表格?如何迭代通过参数进行分析

attach(Liver) 
cor.test(CI, ALAT, method = "spearman") 
cor.test(CI, ASAT, method = "spearman") 
cor.test(CI, GGT, method = "spearman") 
cor.test(CI, Bili, method = "spearman") 
cor.test(CI, LDH, method = "spearman") 
cor.test(CI, FBG, method = "spearman") 

cor.test(CVP, ALAT, method = "spearman") 
cor.test(CVP, ASAT, method = "spearman") 
cor.test(CVP, GGT, method = "spearman") 
cor.test(CVP, Bili, method = "spearman") 
cor.test(CVP, LDH, method = "spearman") 
cor.test(CVP, FBG, method = "spearman") 

cor.test(meanPAP, ALAT, method = "spearman") 
cor.test(meanPAP, ASAT, method = "spearman") 
cor.test(meanPAP, GGT, method = "spearman") 
cor.test(meanPAP, Bili, method = "spearman") 
cor.test(meanPAP, LDH, method = "spearman") 
cor.test(meanPAP, FBG, method = "spearman") 

cor.test(meanSAP, ALAT, method = "spearman") 
cor.test(meanSAP, ASAT, method = "spearman") 
cor.test(meanSAP, GGT, method = "spearman") 
cor.test(meanSAP, Bili, method = "spearman") 
cor.test(meanSAP, LDH, method = "spearman") 
cor.test(meanSAP, FBG, method = "spearman") 

detach("Liver") 

回答

9

有在库ltm函数rcor.test()使相关系数和P值的表。例如使用的数据iris因为没有你的数据框。

library(ltm) 
rcor.test(iris[,1:4],method="spearman") 


      Sepal.Length Sepal.Width Petal.Length Petal.Width 
Sepal.Length *****  -0.167  0.882  0.834  
Sepal.Width 0.041  *****  -0.310  -0.289  
Petal.Length <0.001  <0.001  *****  0.938  
Petal.Width <0.001  <0.001  <0.001  *****  

upper diagonal part contains correlation coefficient estimates 
lower diagonal part contains corresponding p-values 
+7

“Hmisc”中还有'rcorr',它会为您提供单独的相关系数矩阵和p值。 – A5C1D2H2I1M1N2O1R2T1

10

诀窍是获得所有可能的组合。在这里,我创建了一个带有10列的data.frame,并使用combn函数获取所有组合。然后它非常直接地获得corrleation和p-值。

set.seed(12) 
x <- as.data.frame(matrix(rnorm(100), nrow=10)) 
combinations <- combn(ncol(x), 2) 

out <- apply(combinations, 2, function(idx) { 
    t <- cor.test(x[, idx[1]], x[, idx[2]], method = "spearman") 
    c(names(x)[idx[1]], names(x)[idx[2]], t$estimate, t$p.value) 
}) 
# more formatting if necessary 
out <- as.data.frame(t(out)) 
names(out) <- c("col.idx1", "col.idx2", "cor", "pval") 

Edit:甚至更​​紧凑的代码通过利用内combnFUN参数(按照Greg的建议)

set.seed(12) 
x <- as.data.frame(matrix(rnorm(100), nrow=10)) 
out <- as.data.frame(t(combn(ncol(x), 2, function(idx) { 
    t <- cor.test(x[, idx[1]], x[, idx[2]], method = "spearman") 
    c(names(x)[idx[1]], names(x)[idx[2]], t$estimate, t$p.value) 
}))) 
names(out) <- c("col.idx1", "col.idx2", "cor", "pval") 
+2

这就是我应该如何去做的,但是我很欣赏其他作者已经将测试过的代码贡献给知名软件包(如Hmisc)的作品。 –

+2

我不确定,但我想你可能需要使用:t < - cor.test(x [,idx [1]],x [,idx [2]],method ='spearman')来得到答案原来的海报正在寻求。 –

+1

'combn'函数有一个'FUN'参数,所以上面可能可以通过将'apply'中使用的函数直接传递给'combn'来简化。 –