要了解错误尝试通信的原因,请将您的数据与 chisq.test 预期的数据类型进行比较:
dput(matrix(main[1,2:5,drop=T], nrow=2, 2,2))
# structure(list(20, 10, 40, 80), .Dim = c(2L, 2L))
dput(matrix(1:4, nrow=2, 2,2))
# structure(c(1L, 3L, 2L, 4L), .Dim = c(2L, 2L))
一种补救方法是强制您将数据放入numeric 向量中:
res <- chisq.test(matrix(as.numeric(main[1,2:5]), nrow=2, 2,2))
res
# Pearson's Chi-squared test with Yates' continuity correction
# data: matrix(as.numeric(main[1, 2:5]), nrow = 2, 2, 2)
# X-squared = 9.7656, df = 1, p-value = 0.001778
现在,如果您想将结果添加到每一行,您首先需要选择“哪些结果”。也就是说,结果实际上有点美化了,内部有几个花絮:
str(unclass(res))
# List of 9
# $ statistic: Named num 9.77
# ..- attr(*, "names")= chr "X-squared"
# $ parameter: Named int 1
# ..- attr(*, "names")= chr "df"
# $ p.value : num 0.00178
# $ method : chr "Pearson's Chi-squared test with Yates' continuity correction"
# $ data.name: chr "matrix(as.numeric(main[1, 2:5]), nrow = 2, 2, 2)"
# $ observed : num [1:2, 1:2] 20 10 40 80
# $ expected : num [1:2, 1:2] 12 18 48 72
# $ residuals: num [1:2, 1:2] 2.309 -1.886 -1.155 0.943
# $ stdres : num [1:2, 1:2] 3.33 -3.33 -3.33 3.33
如果您想将(例如)测试统计数据包含在一个数字中,您可以这样做:
chisq.statistic <- sapply(seq_len(nrow(main)), function(row) {
chisq.test(matrix(as.numeric(main[row,2:5]), nrow=2, 2,2))$statistic
})
main$chisq.statistic <- chisq.statistic
main
# Genes Group1_Mut Group1_WT Group2_Mut Group2_WT chisq.statistic
# 1 GENE_A 20 40 10 80 9.76562500
# 2 GENE_B 10 50 30 60 4.29687500
# 3 GENE_C 5 55 10 80 0.07716049
请注意,dplyr 和 data.table 之类的工具可能会促进这一点。例如:
library(dplyr)
main %>%
rowwise() %>%
mutate(
chisq.statistic = chisq.test(matrix(c(Group1_Mut, Group1_WT, Group2_Mut, Group2_WT), nrow = 2))$statistic
)
# Source: local data frame [3 x 6]
# Groups: <by row>
# # A tibble: 3 × 6
# Genes Group1_Mut Group1_WT Group2_Mut Group2_WT chisq.statistic
# <fctr> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 GENE_A 20 40 10 80 9.76562500
# 2 GENE_B 10 50 30 60 4.29687500
# 3 GENE_C 5 55 10 80 0.07716049
此示例显示了您可能希望在使用的任何方法中加入的一件事:显式命名列。也就是说,“2:5”可能会根据您的输入矩阵而改变。