在进行卡方检验时修复 for 循环中的列

Fix a column in for loop while doing Chi-square test

我想对以下数据集进行卡方独立性检验。数据集由四个分类变量组成。一次对两个变量执行测试,变量 V4 固定。本质上,我想对 3 种组合执行卡方检验:V1-V4、V2-V4 和 V3-V4。现在,我想循环执行此操作,因为实际分析包括对大量组合的操作。

V1  V2  V3  V4
A   SUV Yes Good
A   SUV No  Good
B   SUV No  Good
B   SUV Yes Satisfactory
C   car Yes Excellent
C   SUV No  Poor
D   SUV Yes Poor
D   van Yes Satisfactory
E   car No  Excellent

我尝试过的:

x <- c(1:3)
for (i in x) {
  test <- chisq.test(df[, i], df[, 4])
  out <- data.frame("X" = colnames(df)[i]
                    , "Y" = colnames(df[4])
                    , "Chi.Square" = round(test$statistic,3)
                    ,  "df"= test$parameter
                    ,  "p.value" = round(test$p.value, 3)
  )
  return(out)
}

但是,我只收到 V1-V4 组合的输出。 代码参考:Chi Square Analysis using for loop in R

out 在每次迭代中都被当前输出替换,OP 得到的结果来自上一次迭代。我们可以使用 listlength 的 'x' 进行初始化,以存储输出

x <- 1:3
out <- vector('list', length(x))
for (i in x) {
test <- chisq.test(df[, i], df[, 4])
out[[i]] <- data.frame("X" = colnames(df)[i]
                , "Y" = colnames(df[4])
                , "Chi.Square" = round(test$statistic,3)
                ,  "df"= test$parameter
                ,  "p.value" = round(test$p.value, 3)
 )

 }

您可以使用lapply来执行这个循环。

x <- 1:3

do.call(rbind, lapply(x, function(i) {
  test <- chisq.test(df[, i], df[, 4])
  data.frame("X" = colnames(df)[i], 
             "Y" = colnames(df[4]), 
             "Chi.Square" = round(test$statistic,3),  
             "df"= test$parameter,  
             "p.value" = round(test$p.value, 3))
})) -> out
rownames(out) <- NULL
out

#   X  Y Chi.Square df p.value
#1 V1 V4      14.25 12   0.285
#2 V2 V4      12.75  6   0.047
#3 V3 V4       2.25  3   0.522