Cal Philic
Cal Philic

Reputation: 11

Fisher test using apply function in R

The following is the code: the problem is that the calculation is very slow.

The matrices, gene1, gene2 and neither are of same length (8000)

pos <- c()
neg <- c()
either <- c()
for(i in 1:ncol(both)){
    x <- cbind(both[,i], gene1[,i], gene2[,i], neither[,i])
    test <- apply(x, 1, function(s){fisher.test(matrix(s, nrow = 2), 
         alternative = "greater")$p.value})
    pos <- c(test,pos)
    test1 <- apply(x, 1, function(s){fisher.test(matrix(s, nrow = 2), 
         alternative = "less")$p.value})
    neg <- c(test1, neg)
    test2 <- apply(x, 1, function(s){fisher.test(matrix(s, nrow = 2))$p.value})
    either <- c(test2, either)
    }

Upvotes: 0

Views: 1850

Answers (1)

joran
joran

Reputation: 173727

You can try using lapply to loop over the different alternatives (less, greater, two.sided) and wrap the fisher.test call in your own function. Perhaps something like this:

myTest <- function(altn,x){
    ft <- apply(x,1,FUN=function(s,alt) {
                        fisher.test(matrix(s,nrow=2),alternative=alt)$p.value},
                        alt=altn)
}

pos <- c()
neg <- c()
either <- c()
for(i in 1:ncol(both)){
    x <- cbind(both[,i], gene1[,i], gene2[,i], neither[,i])
    rs <- lapply(c('two.sided','greater','less'),myTest,x=x)
    pos <- c(rs[[2]],pos)
    neg <- c(rs[[3]],neg)
    either <- c(rs[[1]],either)
}

Without some test data to check on, I can't assure you there won't be any gotcha's in this, but this basic strategy should do what you want.

Note that this still calls fisher.test three times, just in a somewhat more compact form. I don't know of a function that calculates a fisher test with all three alternatives in the same call, but perhaps someone else will weigh in with one.

Upvotes: 1

Related Questions