【问题标题】:Keep multiple values of chisq.test in summarised tibble在汇总的小标题中保留 chisq.test 的多个值
【发布时间】:2019-06-26 15:08:40
【问题描述】:

我已对正在执行卡方检验的数据进行分组,并希望返回一个汇总表,其中包含来自 htest 对象的多个值。例如(from a previous question),

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))

返回 p 值,但我希望将来自 htest 对象的多个值(例如 p.valuestatistic)作为汇总表中的不同列返回。

我试过了

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

但这会引发错误

summarise_impl(.data, dots) 中的错误:
htest 列的长度必须为 1(汇总值),而不是 9

您如何使用 tidyverse 工具完成此任务?

【问题讨论】:

    标签: r dplyr hypothesis-test


    【解决方案1】:

    另一种选择是使用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…
    

    【讨论】:

      【解决方案2】:

      一种方法是 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)
      

      【讨论】:

      • 但那是在每个组上运行两次测试,不是吗?通过将参数 statistic=chisq.test(partido, genero)$statistic 添加到 summarise() 调用中,可以做到完全相同。
      • @merv 你是对的。我已经更新了每组只运行一次测试的答案。不过,我不确定这是否是最好的方法。
      猜你喜欢
      • 2021-04-01
      • 2016-03-14
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      相关资源
      最近更新 更多