R Chi-squared stratified by multiple groups

2019-09-19 02:45发布

问题:

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
# ...