【问题标题】:Calculate cohens d for all pairs of groups in dataframe计算数据框中所有组对的 cohen d
【发布时间】:2019-09-12 00:34:00
【问题描述】:

使用 r 包“effsize”,我试图计算数据中所有组对之间的 cohens d,将所有成对的 d 估计值输出为矩阵。我提供了一些测试数据来说明这一点。我想要一个所有组 1、2 和 3 对的 d 估计矩阵。

我正在努力寻找从哪里开始。我知道可以使用循环来完成,但由于我的真实数据包含 1000 个组,每个组有 6000 个数据点,我认为这会很慢。

library("effsize")

test <- data.frame(
   score=c(2,3,42,1,2,3,4,5,5,6,8,2),
   group=c(1,1,1,1,2,2,2,2,3,3,3,3)
)

这与使用 pairwise.wilcox.test() 为 wilcox 秩和提供的功能类似。

【问题讨论】:

    标签: r


    【解决方案1】:

    您所要做的就是注意函数combn 一次输出n 元素的组合k,并且还可以将函数应用于每个结果组合。在这种情况下,问题要求一次组合 2 个组,并且函数 fun 应用于每个组。

    fun <- function(x) {
      cohen.d(x[[1]]$score, x[[2]]$score)
    }
    
    sp <- split(test, test$group)
    cmb <- combn(sp, 2, fun)
    
    cmb[, 1]
    #[[1]]
    #[1] "Cohen's d"
    #
    #[[2]]
    #[1] "d"
    #
    #[[3]]
    #[1] 0.5992954
    #
    #[[4]]
    #    lower     upper 
    #-1.169345  2.367936 
    #
    #[[5]]
    #[1] 0.95
    #
    #[[6]]
    #[1] medium
    #Levels: negligible < small < medium < large
    

    上面的代码可以写成一个函数来完成所有的工作并返回一个矩阵。

    cohen.d.pairwise.test <- function(DF, scoreCol, groupCol){
      fun <- function(x) {
        eff <- cohen.d(x[[1]][[scoreCol]], x[[2]][[scoreCol]])
        c(eff[["estimate"]],
          eff[["conf.int"]][1],
          eff[["conf.int"]][2],
          eff[["conf.level"]])
      }
      sp <- split(DF, DF[[groupCol]])
      cmb <- combn(sp, 2, fun)
      rownames(cmb) <- c("estimate", "lower", "upper", "conf.level")
      t(cmb)
    }
    
    cohen.d.pairwise.test(test, scoreCol = "score", groupCol = "group")
    #       estimate     lower     upper conf.level
    #[1,]  0.5992954 -1.169345 2.3679357       0.95
    #[2,]  0.4732232 -1.281054 2.2275008       0.95
    #[3,] -0.8795932 -2.691556 0.9323698       0.95
    

    【讨论】:

    • 非常感谢,这太棒了!如果我想将组名添加为前两列,我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2018-11-02
    相关资源
    最近更新 更多