卡方检验的方法

卡方检验是统计两个独立变量之间是否存在相关性的统计方法,比如吸烟和肺癌的关系(率的检验):

03. 卡方检验 - 图1

卡方检验需要矩阵,首先需要构建:

  1. > matrix(c(60,3,32,11), ncol = 2)
  2. [,1] [,2]
  3. [1,] 60 32
  4. [2,] 3 11
  5. > mat = matrix(c(60,3,32,11), ncol = 2)

顺便起个名字呗:

  1. > rownames(mat) = c('smoke', 'not-smoke')
  2. > colnames(mat) = c('cancer', 'uncancer')
  3. > mat
  4. cancer uncancer
  5. smoke 60 32
  6. not-smoke 3 11

直接卡方检验走起~

  1. > chisq.test(mat)
  2. Pearson's Chi-squared test with Yates' continuity correction
  3. data: mat
  4. X-squared = 7.9327, df = 1, p-value = 0.004855

检验阈值如果设置0.05,显然二者相关性很强。

做个练习?

03. 卡方检验 - 图2

列联表的卡方检验

参考:https://www.math.pku.edu.cn/teachers/lidf/docs/Rbook/html/_Rbook/stat-basics.html#stat-base-hyptest-indepcont

其实也就是对分组的事件进行多个描述,判断在不同条件下,检验某因素对某结果是否存在偏好性。多增加几个

比如突变类型与癌症类型偏好的独立性。(重复了两个一样的突变单纯是为了表明其可以有两个及两个以上的分组)

  1. > rbind(ctab_brca1,ctab_brca1)
  2. BLIS IM LAR MES
  3. n-BRCA1 11 4 1 0
  4. NO-n-BRCA1 95 49 55 32
  5. n-BRCA1 11 4 1 0
  6. NO-n-BRCA1 95 49 55 32
  7. > tmp = rbind(ctab_brca1,ctab_brca1)
  8. > chisq.test(tmp)
  9. Pearson's Chi-squared test
  10. data: tmp
  11. X-squared = 14.025, df = 9, p-value = 0.1215

在0.05水平下认为癌症类型与突变类别无关。

另外,addmargins 函数非常好用,可以计算行与列的加和,而prop.table 则可以计算该位置数目所占总数的比重:

  1. tab2 <- round(prop.table(addmargins(ctab_brca1, 1), 1), 3)
  2. > tab2
  3. BLIS IM LAR MES
  4. n-BRCA1 0.688 0.250 0.062 0.000
  5. NO-n-BRCA1 0.411 0.212 0.238 0.139
  6. Sum 0.429 0.215 0.227 0.130