Skip to content

Instantly share code, notes, and snippets.

@shinout
Created July 30, 2018 14:59
Show Gist options
  • Select an option

  • Save shinout/57d0b3c92bdd36f84d25e5783be77184 to your computer and use it in GitHub Desktop.

Select an option

Save shinout/57d0b3c92bdd36f84d25e5783be77184 to your computer and use it in GitHub Desktop.
Calculate chi square values from n x m table
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
@shinout
Copy link
Copy Markdown
Author

shinout commented Jul 30, 2018

Just remove console.log!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment