【问题标题】:Fix a column in for loop while doing Chi-square test在进行卡方检验时修复 for 循环中的列
【发布时间】:2021-06-25 22:59:09
【问题描述】:

我想对以下数据集执行卡方独立性检验。数据集由四个分类变量组成。在固定变量 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

【问题讨论】:

    标签: r for-loop chi-squared


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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
      

      【讨论】:

        猜你喜欢
        • 2013-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-11
        相关资源
        最近更新 更多