【问题标题】:Chi-square statistic across multiple columns of a dataframe using dplyr or reshape2使用 dplyr 或 reshape2 跨数据帧多列的卡方统计
【发布时间】:2023-03-09 07:52:01
【问题描述】:

我有一个关于使用dplyrreshape2 计算跨多个列的卡方统计数据的问题。下面是一个小数据框...

Sat <- c("Satisfied","Satisfied","Dissatisfied","Dissatisfied",
                                       "Neutral")

Gender <- c("Male","Male","Female","Male","Female")

Ethnicity <- c("Asian","White","White","Asian","White")

AgeGroup <- c("18-20","18-20","21-23","18-20","18-28")

Example <- data.frame(Sat,Gender,Ethnicity,AgeGroup)

我将如何使用 summarise_eachmelt 针对其他每个变量计算 Sat 列,以生成卡方残差和 p 值统计信息。我想一定有类似的东西:

Example %>% summarise_each(funs(chisq.test(... 

但我不确定如何完成它。另外,我将如何融化数据框并使用group_bydo() 来获取卡方统计信息?我有兴趣看到这两种方法。如果有办法合并broom 包,那也很好,或者tidyr 而不是reshape2

回顾一下,我想运行卡方检验,例如

chisq.test(Example$Sat, Example$Gender)

但是...我想针对GenderEthnicityAgeGroup 生成Sat 变量的卡方统计信息。这是一个小例子,我希望上面的方法能够让我以快速有效的方式跨多列创建卡方统计数据。如果我可以使用ggplot2 在热图中绘制残差,那将是一个奖励,这就是为什么我有兴趣将broom 包合并到这个示例中。

【问题讨论】:

  • Sat 中有句点应该是逗号;它不会按原样运行。

标签: r dplyr reshape2 broom


【解决方案1】:

如果我们需要获取p values

 Example %>% 
    summarise_each(funs(chisq.test(., 
               Example$Sat)$p.value), -one_of("Sat"))
 #     Gender Ethnicity  AgeGroup
 #1 0.2326237 0.6592406 0.1545873

或者提取statistic

Example %>%
    summarise_each(funs(chisq.test(., 
           Example$Sat)$statistic), -one_of("Sat"))
#   Gender Ethnicity AgeGroup
#1 2.916667 0.8333333 6.666667

要获得residuals,使用base R 会更容易

 lapply(Example[setdiff(names(Example), "Sat")], 
       function(x) chisq.test(x, Example$Sat)$residuals)

【讨论】:

  • 感谢您的详细回答,他们工作得很好!只有一个问题,我对“setdiff”不熟悉,它的目的是什么?
  • @Mike setdiff 的目的是返回第一个向量中不在第二个向量中的元素。在示例中,它应该返回除“Sat”之外的所有列名。
  • 嗨 Akrun,现在 summarise_each 已被弃用,我正在尝试使用 summarise_at(,.vars = (1:4),) 但我收到此错误:.vars must be a character/numeric向量
  • @Shub 使用summarise_at(1:4, funs(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 2017-12-24
  • 1970-01-01
  • 2023-02-16
  • 2015-05-06
  • 1970-01-01
相关资源
最近更新 更多