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

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

提问人:vp_050 提问时间:3/30/2021 更新时间:8/11/2022 访问量:881

问:

我想对以下数据集执行独立性卡方检验。数据集由四个分类变量组成。测试一次对两个变量执行,变量 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 组合的输出。 代码参考:在 R 中使用 for 循环的卡方分析

R for 循环 卡方

评论


答:

3赞 akrun 3/30/2021 #1

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

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))
  
 }
1赞 Ronak Shah 3/30/2021 #2

您可以使用它来执行此循环。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