tidyverse:Chi Square适用于所有列的组合

问题描述 投票:0回答:1

我使用以下代码对所有可能的列组合进行卡方分析。

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进行同样的操作。任何提示。

r dplyr plyr tidyverse chi-squared
1个回答
2
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.