A javascript implementation of the non-central version of Fisher’s exact test

A javascript implementation of the non-central version of Fisher’s exact test

In a previous post, I presented a case for choosing a non-central version of Fisher’s exact test for most of bioinformatics’ uses of this test. I will now present an implementation of this test in javascript that could easily be embedded in web interfaces.

Although javascript is probably the least likely language to implement statistical methods, I hope this article will fill in as many details as possible to make it trivial to port it to other languages if the need arises. At the very least, it should demystify the inner working of this extremely useful test. I’ll limit myself to the context of $2\times 2$ contingency tables. Finally, I must admit that I was pleasantly surprised by the performance of this code!

Here, deciding on an $x$ allows to fill the table using the sums. The p-value of Fisher’s exact test is then computed by adding the probabilities for scenarios where $x$ is greater than the observed $n_{11}$. This is stored as “den_sum” and computed by the last “for” loop of the function. Notice that all sums are done using scaled probabilities (- max_l in log-space), this avoids summing over very small numbers and risking an underflow. Since the final p-value is the result of a ratio, the scaling factor cancels itself out in Math.exp (den_sum – sum_l). Finally, “w” is used to pass the odds ratio threshold ($\omega$) required.

Please be advised that this code has been only very lightly tested. I confirmed that it returns identical results to the R implementation (fisher.exact) on a limited number of non-trivial test cases. If you find any issue, I’d be happy to investigate!