Groovy web console

subscribe to the feed Subscribe
to this
site
embed in your blog Embed
this
script
Fisher Exact Test for MxN matrices (via #groovywebconsole)
tweet this snippet Tweet
this
script

To embed this script in your site, just drop the content below where you want to embed it.

Fisher Exact Test for MxN matrices

Published 1 month ago by Matt Stine with tags statistical test
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def fact(BigInteger n) {
    (n == 0 || n == 1) ? 1 : n * fact(n-1)
}

def fisherExactTest(def matrix) {
    def rowSums = []
    def colSums = [] 
    
    matrix.eachWithIndex { row, i ->
        rowSums[i] = row.sum()
        
        row.eachWithIndex { val, j ->
            colSums[j] = colSums[j] == null ? val : colSums[j] + val
        }
    }
    
    def totalSum = rowSums.sum()
    
    def factorialProduct = { x, y ->
        x * fact(y)
    }
    
    (rowSums.inject(1, factorialProduct) * colSums.inject(1, factorialProduct)) / (fact(totalSum) * matrix.flatten().inject(1, factorialProduct))
}

println fisherExactTest([[5, 0],[1, 4]])
println fisherExactTest([[15, 20, 15],[20, 25, 5]])

Recent scripts