您已经很接近了,只需使用 str 检查一个测试即可帮助您决定选择哪些元素。
apply(dat[,c('female_boxing','female_cycling','male_boxing','male_cycling')],
1, function(x) chisq.test(x)[c('statistic', 'p.value')] )
apply 为您提供了一个列表,使用sapply 并循环遍历行,结果会更好一些。
chi <- t(sapply(seq(nrow(dat)), function(i)
chisq.test(dat[i, c('female_boxing','female_cycling','male_boxing','male_cycling')])[
c('statistic', 'p.value')]))
cbind(dat, chi)
# ID1 ID2 female_boxing female_cycling male_boxing male_cycling statistic p.value
# 1 A zit 43 170 159 710 988.7209 5.033879e-214
# 2 B tag 37 134 165 744 1142.541 2.146278e-247
# 3 C hfs 32 96 170 784 1334.991 3.762222e-289
# 4 D prt 17 61 185 811 1518.015 0
# 5 E its 31 112 169 762 1245.218 1.133143e-269
# 6 F qrw 68 233 130 645 752.3941 9.129485e-163
数据:
dat <- structure(list(ID1 = c("A", "B", "C", "D", "E", "F"), ID2 = c("zit",
"tag", "hfs", "prt", "its", "qrw"), female_boxing = c(43L, 37L,
32L, 17L, 31L, 68L), female_cycling = c(170L, 134L, 96L, 61L,
112L, 233L), male_boxing = c(159L, 165L, 170L, 185L, 169L, 130L
), male_cycling = c(710L, 744L, 784L, 811L, 762L, 645L)), class = "data.frame", row.names = c(NA,
-6L))