我有一个关于使用dplyr
和reshape2
计算多列卡方统计的问题。下面是一个小数据帧。。。
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_each
或melt
来针对每个其他变量计算Sat
列,以生成卡方残差和p值统计数据。我想肯定有这样的东西:
Example %>% summarise_each(funs(chisq.test(...
但我不知道如何完成。此外,我如何融化数据帧并使用group_by
或do()
来获得卡方统计数据?我对这两种方法都感兴趣。如果有办法合并broom
包,那也太好了,或者用tidyr
代替reshape2
。
概括一下,我想进行卡方测试,比如
chisq.test(Example$Sat, Example$Gender)
但是。。。我想针对Gender
、Ethnicity
和AgeGroup
生成Sat
变量的卡方统计数据。这是一个小例子,我希望上面的方法能让我以快速有效的方式在许多列中创建卡方统计数据。如果我能用ggplot2
在热图中绘制残差,这就是为什么我有兴趣将broom
包合并到这个例子中。
如果我们需要获得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)