Fisher's exact test on values from large dataframe and bypassing errors

后端 未结 1 1549
再見小時候
再見小時候 2021-01-14 22:24

I have a dataframe which is 214 columns long and many rows long, and I want to perform a fisher\'s exact test for each row using values from 4 columns.

An example s

相关标签:
1条回答
  • 2021-01-14 23:19

    You can include an if-else statement in your loop like this:

    res <- NULL
    for (i in 1:nrow(df)){
      table <- matrix(c(df[i,4], df[i,5], df[i,2], df[i,3]), ncol = 2, byrow = TRUE)
    # if any NA occurs in your table save an error in p else run the fisher test
      if(any(is.na(table))) p <- "error" else p <- fisher.test(table, alternative="greater")$p.value
      # save all p values in a vector
      res <- c(res,p)
    }
    df$fishers <- res
    

    Or put the code in a function and use apply instead of a loop:

    foo <- function(y){
      # include here as.numeric to be sure that your values are numeric:
      table <-  matrix(as.numeric(c(y[4], y[5], y[2], y[3])), ncol = 2, byrow = TRUE)
      if(any(is.na(table))) p <- "error" else p <- fisher.test(table, alternative="greater")$p.value
      p
    } 
    df$fishers <- apply(df, 1, foo)
    
    0 讨论(0)
提交回复
热议问题