Chi-square在dplyr中使用分组数据进行测试

时间:2018-03-16 12:04:26

标签: r dplyr chi-squared

总结data.frame总结如此困难:

db <- data.frame(ID = c(rep(1, 3), rep(2,4), rep(3, 2), 4),
             Gender = factor(c(rep("woman", 7), rep("man", 2), "woman")),
             Grade = c(rep(3, 3), rep(1, 4), rep(2, 2), 1),
             Drug = c(1, 2, 2, 1, 2, 6, 9, 8, 5, 1),
             Group = c(rep(1, 3), rep(2,4), rep(1, 2), 2))
db

#    ID Gender Grade Drug Group
# 1   1  woman     3    1     1
# 2   1  woman     3    2     1
# 3   1  woman     3    2     1
# 4   2  woman     1    1     2
# 5   2  woman     1    2     2
# 6   2  woman     1    6     2
# 7   2  woman     1    9     2
# 8   3    man     2    8     1
# 9   3    man     2    5     1
# 10  4  woman     1    1     2

理想情况下,每次观察我会有一行,但因为Drugs会随着时间的推移而变化,所以我最终会有很多重复的行。这使我的分析变得困难。

我的最终目标是构建一个摘要表,如另一篇文章中所述:Using dplyr to create summary proportion table with several categorical/factor variables。像这样:

|变量|第1组|第2组|差异组1/2 |
| 性别 ................................ | ......................... p = 1 |
|男....... ........... 1 | ............ 0 | .................................. |
|女。 | ........... 1 | ............. 2 | ..................... .............. |

但是,由于这篇文章只是部分回答并且不能直接适用于我的问题(主要是由于重复的行),如果可以单独执行摘要统计,我会很高兴。在这篇文章中:How to get the frequency from grouped data with dplyr?我问如何从观察中获得独特/不同的频率。现在,我需要找出两组之间性别分布是否存在统计学显着差异

根据ID,我知道有四个观察结果,其中三个是女性,一个是男性。所以期望的结果可以这样计算:

gen <- factor(c("woman", "woman", "man", "woman"))
gr <- c(1, 2 ,1 ,2)
chisq.test(gen, gr)

#   Pearson's Chi-squared test with Yates' continuity correction
# 
# data:  gen and gr
# X-squared = 0, df = 1, p-value = 1
#
# Warning message:
# In chisq.test(gen, gr) : Chi-squared approximation may be incorrect

如何使用data.frame从我的dplyr计算p-vale?

我的失败方法是:

db %>% 
  group_by(ID) %>% 
  distinct(ID, Gender, Group) %>% 
  summarise_all(funs(chisq.test(db$Gender, 
                               db$Group)$p.value))
# A tibble: 4 x 3
#      ID Gender Group
#  <dbl>  <dbl> <dbl>
# 1    1.  0.429 0.429
# 2    2.  0.429 0.429
# 3    3.  0.429 0.429
# 4    4.  0.429 0.429
# Warning messages:
# 1: In chisq.test(db$Gender, db$Group) :
#   Chi-squared approximation may be incorrect
# 2: In chisq.test(db$Gender, db$Group) :
#   Chi-squared approximation may be incorrect
# 3: In chisq.test(db$Gender, db$Group) :
#  Chi-squared approximation may be incorrect
# 4: In chisq.test(db$Gender, db$Group) :
#  Chi-squared approximation may be incorrect
# 5: In chisq.test(db$Gender, db$Group) :
#   Chi-squared approximation may be incorrect
# 6: In chisq.test(db$Gender, db$Group) :
#  Chi-squared approximation may be incorrect
# 7: In chisq.test(db$Gender, db$Group) :
#  Chi-squared approximation may be incorrect
# 8: In chisq.test(db$Gender, db$Group) :
#  Chi-squared approximation may be incorrect

1 个答案:

答案 0 :(得分:1)

我们可以ungroup然后使用pvalue

获取summarise
db %>% 
  group_by(ID) %>% 
  distinct(ID, Gender, Group) %>%
  ungroup %>%
  summarise(pval = chisq.test(Gender, Group)$p.value)