Home > Software engineering >  Perform multiple fisher tests on multiple columns
Perform multiple fisher tests on multiple columns

Time:12-14

I have data set like this:

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

I want to perform fisher exact test so I can test P1 with A1,B1,C1 and then test P2 with A1,B1,C1 and then P3 with A1,B1,C1. An example of the first test is :

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

I have large data set so if you can help me please to do it in one code would be great. I know how to test P1 against A1,B1 and C1 but I cannot do it for P2 and P3 with the same code. Any help is appreciated.

CodePudding user response:

A solution using broom::tidy for an easy representation of test results in a data.frame

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  
  •  Tags:  
  • r
  • Related