Looping correlation tests on same variables across more than two dataframes

拥有回忆 提交于 2020-01-17 03:17:21

问题


Consider these three dataframes:

df1 <- data.frame(a = runif(10,1,10), b = runif(10,1,10), c = runif(10,1,10))

df2 <- data.frame(a = runif(10,1,10), b = runif(10,1,10), c = runif(10,1,10))

df3 <- data.frame(a = runif(10,1,10), b = runif(10,1,10), c = runif(10,1,10))

I want to do a cor.test between column a against column a, b against b and c against c in all dfs – I can do it between each pair using and modifying code below but I want loop between all three dataframes in one go:

for (i in 1:length(df1)){

    cor.test(df1[,i],df2[,i])

}

How would I go about doing that?


回答1:


We could do the combination of object names with combn, get the values with mget in a list, and apply cor.test on each list and extract the p.value

combn(paste0("df", 1:3), 2, FUN = function(x) {
      x1 <- mget(x, envir = .GlobalEnv)
     Map(function(x,y) cor.test(x,y)$p.value, x1[[1]], x1[[2]])})

Or another option is corr.test from psych

library(psych)
t(sapply(names(df1), function(nm) {
     x1 <- corr.test(data.frame(df1[nm], df2[nm], df3[nm]))$p
      x1[lower.tri(x1)]})))


来源:https://stackoverflow.com/questions/40819971/looping-correlation-tests-on-same-variables-across-more-than-two-dataframes

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