【问题标题】:Chi square matrix residuals卡方矩阵残差
【发布时间】:2022-01-13 23:38:35
【问题描述】:

下面是一个从多个卡方检验中提取 p 值并将它们显示为矩阵的函数。我正在尝试做同样的事情,但要提取残差。任何帮助表示赞赏。

样本数据:

df <- data.frame(first_column  = c(rep("E1_C1",5), rep("E1_C2",3), rep("E2_C2",7),rep("E3_C3",5)),
                  second_column = c(rep("E1_C1",3), rep("E1_C2",10), rep("E2_C2",4),rep("E3_C3",3)),
                  third_column = c(rep("E1_C1",7), rep("E1_C2",4), rep("E2_C2",3),rep("E3_C3",6)),
                  fourth_column = c(rep("E1_C1",4), rep("E1_C2",6), rep("E2_C2",6),rep("E3_C3",4))
)

P 值的卡方矩阵函数:

chisqmatrix <- function(x) {
  names = colnames(x);  num = length(names)
  m = matrix(nrow=num,ncol=num,dimnames=list(names,names))
  for (i in 1:(num-1)) {
    for (j in (i+1):num) {
      #browser()
      m[j,i] = chisq.test(x[, i, drop = TRUE],x[, j, drop = TRUE])$p.value
    }
  }
  return (m)
}

生成卡方 p 值矩阵

res <- chisqmatrix(df)
res[, -ncol(res)]

【问题讨论】:

  • combn(df, 2, function(x) chisq.test(x[[1]], x[[2]])[['residuals']], simplify = FALSE)
  • @Onyambu 谢谢。但是,有没有办法让它更具可读性(例如 col 和 row 名称)。例如,上面的最后两行代码显示了类似于相关矩阵的内容。我想最终生成一个类似于这里所做的残差图 - sthda.com/english/wiki/chi-square-test-of-independence-in-r

标签: r statistics chi-squared


【解决方案1】:

在您的情况下,返回的残差是一个 4x4 矩阵。以下解决方案不是使用矩阵来获取结果,而是使用列表。这样您就可以拥有不同大小的矩阵。

对原始代码的改动很小:

chisqlist <- function(x) {
  names = colnames(x);  num = length(names)
  m = list()
  index = 1
  for (i in 1:(num-1)) {
    for (j in (i+1):num) {
      #browser()
      m[[index]] = chisq.test(x[, i, drop = TRUE],x[, j, drop = TRUE])$residuals
      index=index+1
    }
  }
  return (m)
}

编辑: 我确实更喜欢@ Onyambu 的答案,我没有看到。它会比嵌套的 for 循环更快。

【讨论】:

    【解决方案2】:

    只需将您的函数从请求 $p.value 更改为请求 $residuals。这将提供(观察到 - 预期)/ sqrt(预期)。如果您需要标准化残差,请请求 $stdres。

      chisqmatrix <- function(x) {
        names = colnames(x);  num = length(names)
        m = matrix(nrow=num,ncol=num,dimnames=list(names,names))
        for (i in 1:(num-1)) {
          for (j in (i+1):num) {
            #browser()
            m[j,i] = chisq.test(x[, i, drop = TRUE],x[, j, drop = TRUE])$residuals
          }
        }
        return (m)
      }
    

    【讨论】:

    • 你知道残差是一个向量吗?而m[i, j] 只接受一个值。所以这是不正确的
    猜你喜欢
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多