明白爲什麼錯誤是試圖傳達的信息,數據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」可能會根據您的輸入矩陣而變化。
打了我33秒...... ;-) – r2evans
可能是因爲我放鬆了一些細節。 :) – Benjamin
80%「現在」與95%33秒「太晚」... – r2evans