Created
July 30, 2018 14:59
-
-
Save shinout/57d0b3c92bdd36f84d25e5783be77184 to your computer and use it in GitHub Desktop.
Calculate chi square values from n x m table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function chiSquareValue(values, separateBy = 2) { | |
if (values.length % separateBy !== 0) { | |
throw new Error(`Illegal separation rule. values.length ${valus.length} cannot be divided by ${separateBy}.`) | |
} | |
const sum = values.reduce((acc, val) => acc + val, 0) | |
const rowSums = [] | |
const colSums = [] | |
return values.reduce((chiSq, val, i) => { | |
const row = Math.floor(i / separateBy) | |
const col = i % separateBy | |
if (rowSums[row] == null) { | |
rowSums[row] = values.slice(row * separateBy, (row + 1) * separateBy).reduce((acc, val) => acc + val, 0) | |
} | |
if (colSums[col] == null) { | |
colSums[col] = values.filter((val, j) => j % separateBy === col).reduce((acc, val) => acc + val, 0) | |
} | |
const rowSum = rowSums[row] | |
const colSum = colSums[col] | |
const expected = rowSum * colSum / sum | |
const chiSqPart = Math.pow(val - expected, 2) / expected | |
console.log({ i, val, row, col, rowSum, colSum, expected, chiSqPart }) | |
return chiSq + chiSqPart | |
}, 0) | |
} | |
module.exports = chiSquareValue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just remove
console.log
!