对多个列执行多个Fisher测试

kqlmhetl  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(129)

我有这样的数据集:

df<-data.frame(ID=c(1:5),P1=c("A","A","A","B","B"),P2=c("T","T","C","N","R"),P3=c("G","G","G","B","B"),A1=c("Present","Present","Present","absent","absent"),
               B1=c("absent","Present","Present","absent","absent"),C1=c("absent","absent","Present","absent","absent") )
df

我想执行Fisher精确检验,这样我就可以用A1、B1、C1检验P1,然后用A1、B1、C1检验P2,再用A1、B1、C1检验P3。

fisher<-with(df, table(P1, A1))
fisher
fisher_test(fisher)

我有大的数据集,所以如果你能帮助我,请在一个代码将是伟大的。我知道如何测试对A1,B1和C1的P1,但我不能用相同的代码为P2和P3。任何帮助,不胜感激。

tzdcorbm

tzdcorbm1#

一个使用broom::tidy的解决方案,用于在 Dataframe 中轻松表示测试结果。

library(dplyr)
library(tidyr)
library(broom)

df |>
    pivot_longer(P1:P3,
                 values_to = "tst1",
                 names_to = "P") |>
    pivot_longer(c(A1,B1,C1),
                 values_to = "tst2",
                 names_to = "A") |>
    group_by(A,P) |>
    group_modify(~with(.x, tidy(fisher.test(table(tst1, tst2)))))

+ # A tibble: 9 × 8
# Groups:   A, P [9]
  A     P     estimate p.value conf.low conf.high method             alternative
  <chr> <chr>    <dbl>   <dbl>    <dbl>     <dbl> <chr>              <chr>      
1 A1    P1           0     0.1   0           2.74 Fisher's Exact Te… two.sided  
2 A1    P2          NA     0.4  NA          NA    Fisher's Exact Te… two.sided  
3 A1    P3         Inf     0.1   0.365     Inf    Fisher's Exact Te… two.sided  
4 B1    P1           0     0.4   0           8.23 Fisher's Exact Te… two.sided  
5 B1    P2          NA     1    NA          NA    Fisher's Exact Te… two.sided  
6 B1    P3         Inf     0.4   0.122     Inf    Fisher's Exact Te… two.sided  
7 C1    P1           0     1     0          58.4  Fisher's Exact Te… two.sided  
8 C1    P2          NA     0.6  NA          NA    Fisher's Exact Te… two.sided  
9 C1    P3         Inf     1     0.0171    Inf    Fisher's Exact Te… two.sided

相关问题