在汇总的标题中保留 chisq.test 的多个值

Keep multiple values of chisq.test in summarised tibble

我对正在执行 chi-squared 测试的数据进行了分组,并希望返回一个摘要 table,其中包括来自 htest object 的多个值。例如 (),

library(dplyr)

set.seed(1)
foo <- data.frame(
  partido=sample(c("PRI", "PAN"), 100, 0.6),
  genero=sample(c("H", "M"), 100, 0.7), 
  GM=sample(c("Bajo", "Muy bajo"), 100, 0.8)
)

foo %>% 
  group_by(GM) %>% 
  summarise(p.value=chisq.test(partido, genero)$p.value))

returns p-value,但我想要 htest object 中的多个值(比如 p.valuestatistic)在摘要 table.

中作为不同的列返回

我试过了

foo %>%
  group_by(GM) %>%
  summarise(htest=chisq.test(partido, genero)) %>%
  mutate(p.value=htest$p.value, statistic=htest$statistic)

但这会引发错误

Error in summarise_impl(.data, dots) :
Column htest must be length 1 (a summary value), not 9

如何使用 tidyverse 工具完成此操作?

一种方法是按组 nest 数据 (GM),然后使用 map 从每个组中获取不同的值。

library(tidyverse)

foo %>%
  group_by(GM) %>%
  nest(partido, genero) %>%
  ungroup() %>%
  mutate(p.value = map_dbl(data, ~ chisq.test(.$partido,.$genero)$p.value), 
        statistic = map_dbl(data, ~ chisq.test(.$partido,.$genero)$statistic)) %>%
  select(-data)

#    GM       p.value statistic
#  <fct>      <dbl>     <dbl>
#1 Bajo       0.900    0.0157
#2 Muy bajo   0.478    0.504 

或者如果我们只想 运行 测试一次,我们可以将对象存储在一个变量中并提取感兴趣的值。

foo %>%
  group_by(GM) %>%
  nest(partido, genero) %>%
  ungroup() %>%
  mutate(obj = map(data, ~ chisq.test(.$partido,.$genero)), 
         p.value = map_dbl(obj, ~ .$p.value), 
         statistic = map_dbl(obj, ~ .$statistic)) %>%
  select(-data, -obj)

另一种选择是利用broom::tidy

library(broom)
library(tidyverse)
foo %>%
    group_by(GM) %>%
    nest() %>%
    transmute(
        GM,
        res = map(data, ~tidy(chisq.test(.x$partido, .x$genero)))) %>%
    unnest()
## A tibble: 2 x 5
#  GM      statistic p.value parameter method
#  <fct>       <dbl>   <dbl>     <int> <chr>
#1 Bajo       0.0157   0.900         1 Pearson's Chi-squared test with Yates' c…
#2 Muy ba…    0.504    0.478         1 Pearson's Chi-squared test with Yates' c…