R Chi-squared stratified by multiple groups

霸气de小男生 提交于 2019-12-11 23:57:40

问题


I've the following df with 3 factors variables and one percentage variable:

  df <- data.frame(
    group = rep(c("Case", "Control"), each=16),
    timing = rep(c("T0", "T1", "T2", "T3"), each=4, times=2),
    food.type = rep (c("Very healthy", "Healthy", "Unhealthy", "Very bad"), times = 8),
    intake.percentage = runif(32, min=1, max=25)
)

How do I perform the test (chi squared) in order to evaluate statistical difference each time (T0-T3) between groups (case; controls) for each kind of food?

For your convenience the plot that could help you understand:

ggplot(df, aes(x = timing,y = intake.percentage, group=group)) +

geom_line(aes(colour=group)) +
geom_point(aes(colour=group, shape=group), size=3) +
theme_light(16) +

facet_grid(facets = .~food.type, scales = 'free')


回答1:


For the programmatic part of it (Stackoverflow for programming problems, Cross Validated for statistical problems), assuming you got 100 trials for each scenario:

set.seed(1)
df <- data.frame(
  group = rep(c("Case", "Control"), each=16),
  timing = rep(c("T0", "T1", "T2", "T3"), each=4, times=2),
  food.type = rep (c("Very healthy", "Healthy", "Unhealthy", "Very bad"), times = 8),
  intake.percentage = runif(32, min=1, max=25)
)
lst <- with(df, split(transform(df, intake.percentage2=100-intake.percentage), list(timing, food.type)))
res <- lapply(lst, function(x) chisq.test(x[, -(1:3)]))
sapply(res, "[", "p.value")
# $T0.Healthy.p.value
# [1] 0.009604491
# 
# $T1.Healthy.p.value
# [1] 0.001794137
# 
# $T2.Healthy.p.value
# [1] 0.04958723
# 
# $T3.Healthy.p.value
# [1] 0.9904441
# 
# $T0.Unhealthy.p.value
# [1] 0.4369428
# ...


来源:https://stackoverflow.com/questions/35393156/r-chi-squared-stratified-by-multiple-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!