代码之家  ›  专栏  ›  技术社区  ›  MYaseen208

tidyverse:所有列组合的卡方

  •  0
  • MYaseen208  · 技术社区  · 6 年前

    Dat <- esoph[ , 1:3]
    
    library(plyr)
    
    combos <- combn(ncol(Dat),2)
    
    adply(combos, 2, function(x) {
      test <- chisq.test(Dat[, x[1]], Dat[, x[2]])
    
      out <- data.frame("Row" = colnames(Dat)[x[1]]
                        , "Column" = colnames(Dat[x[2]])
                        , "Chi.Square" = round(test$statistic,3)
                        ,  "df"= test$parameter
                        ,  "p.value" = round(test$p.value, 3)
      )
      return(out)
    
    })  
    
      X1   Row Column Chi.Square df p.value
    1  1 agegp  alcgp      1.419 15       1
    2  2 agegp  tobgp      2.400 15       1
    3  3 alcgp  tobgp      0.619  9       1
    

    我想知道怎样才能做到这一点 tidyverse . 任何提示。

    1 回复  |  直到 6 年前
        1
  •  2
  •   AntoniosK    6 年前
    Dat <- esoph[, 1:3]
    
    library(tidyverse)
    library(broom)
    
    data.frame(t(combn(names(Dat),2)), stringsAsFactors = F) %>%
      mutate(d = map2(X1, X2, ~tidy(chisq.test(Dat[,.x], Dat[,.y])))) %>%
      unnest()
    
    #      X1    X2 statistic   p.value parameter                     method
    # 1 agegp alcgp 1.4189096 0.9999971        15 Pearson's Chi-squared test
    # 2 agegp tobgp 2.4000000 0.9999022        15 Pearson's Chi-squared test
    # 3 alcgp tobgp 0.6194617 0.9999240         9 Pearson's Chi-squared test