chisq.test 对于四个数字的每一行并在 R 中的新数据框中输出

chisq.test for each row on four numbers and output in new data frame in R

我有一个数据框,其中每一行都包含一个意外事件 table 的数字,我想在其中 运行 一个 chisq.test 命令(对数据框中的每一行) R. 每行的输出应作为新列(X 平方值,p 值)添加到数据框中。

DF1:

ID1 ID2 female_boxing female_cycling male_boxing male_cycling 
A zit 43 170 159 710
B tag 37 134 165 744
C hfs 32 96 170 784
D prt 17 61 185 811
E its 31 112 169 762
F qrw 68 233 130 645

这是我试过的:

apply(DF1[,c('female_boxing','female_cycling','male_boxing','male_cycling')], 1, function(x) chisq.test(x) )

但这只给我每行的摘要 table。

您很接近,只需使用 str 检查一项测试,这有助于您决定要 select 的元素。

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))