计算每列中的总数,然后 运行 在 R 中进行渔民测试

calculate totals in each column and then run a fishers test in R

数据:

variant disease control total
A1         1      53    54
A2         6      2     8
A3         15     37    52
A4         0      53    53
A5         65     4     69
A6         4      5     9
A7         3      34    37

我想在底部添加一行,其中包含疾病和对照列的总计,然后 运行 每行添加另一列,其中包含测试的 p 值。

期望的结果(p 值组成):

variant disease control total p-value
A1         1      53    54    0.001
A2         6      2     8     0.6921
A3         15     37    52    1
A4         0      53    53    0.98
A5         65     4     69    0.68
A6         4      5     9     0.63
A7         3      34    37    0.832
C_total    94     188

我试过:

rbind(df, colSums(df[,2:3]), fill=TRUE) 

但这给了我最后两列中的所有列总数

还不确定 Fishers,但想象一下某种形式的应用函数使用每行和每总数来创建 2x2 table。

非常感谢

对于您的第一个问题:

rbind(df, rbind(colSums(df[,2:3])), fill = TRUE)[ (.N == seq_len(.N)), variant := "Total"][]
#    variant disease control total p-value
# 1:      A1       1      53    54  0.0010
# 2:      A2       6       2     8  0.6921
# 3:      A3      15      37    52  1.0000
# 4:      A4       0      53    53  0.9800
# 5:      A5      65       4    69  0.6800
# 6:      A6       4       5     9  0.6300
# 7:      A7       3      34    37  0.8320
# 8:   Total      94     188    NA      NA

一个dplyrtibble的解决方案可以是:

df %>%
 add_row(variant = "Total", !!!colSums(df[-1])) %>%
 rowwise() %>%
 mutate(p_value = chisq.test(c_across(c(disease, control)), p = c(0.5, 0.5))$p.value)

  variant disease control total  p_value
  <chr>     <dbl>   <dbl> <dbl>    <dbl>
1 A1            1      53    54 1.48e-12
2 A2            6       2     8 1.57e- 1
3 A3           15      37    52 2.28e- 3
4 A4            0      53    53 3.34e-13
5 A5           65       4    69 2.08e-13
6 A6            4       5     9 7.39e- 1
7 A7            3      34    37 3.46e- 7
8 Total        94     188   282 2.17e- 8

而且我假设您尝试比较两组之间的个体数量是否相同,可以使用 chi-square 拟合优度检验。