How to iterate through parameters to analyse

别来无恙 提交于 2019-11-29 12:44:10

There is a function rcor.test() in library ltm that makes table of correlation coefficients and p-values. For example used data iris as do not have your data frame.

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

The trick is to get all possible combinations. Here, I create a data.frame with 10 columns and get all combinations using the combn function. Then its pretty straightforward to obtain the corrleation- and p- values.

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: An even more compact code by utilizing FUN argument within combn (as per Greg's suggestion)

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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!