chi-square test demo

statinfer (opens in a new tab) is a JavaScript package for statistical tests, with TypeScript types included. It runs in Node.js and in the browser.

This page demonstrates its chiSquareTest function, which tests counts in categories. Enter your own counts below: statinfer calculates the result right here in your browser, explains what it means, and shows the JavaScript code that produces it.

On this page: When to use a chi-square test ยท Demo data ยท Demo results ยท What the results mean ยท How to use it ยท Further reading

When to use a chi-square test

A chi-square test works with counts: how many things fall into each category. It compares the counts you observed with the counts you'd expect if nothing interesting were going on. There are two kinds:

The test relies on an approximation that needs reasonably large counts. A common rule of thumb is an expected count of at least 5 in each cell. For 2ร—2 tables with small counts, Fisher's exact test is more reliable. For 2ร—2 tables, statinfer applies Yates' continuity correction by default, like SciPy and R, which makes the test slightly more cautious. You can turn it off in the demo.

Demo data

Demo results

Chi-square test of independence (Yates' correction)
===================================================
statistic  4.812
p-value    0.02826
df         1

What the results of a chi-square test mean

The chi-square statistic from the demo data entered above is 4.812, with 1 degrees of freedom.

If the rows and columns are unrelated, the chance of getting a result at least this extreme is 0.02826. That's the p-value.

That's below 0.05, so at the common 5% level this counts as evidence that the rows and columns are related.

How to use statinfer's chi-square test in your JavaScript code

Install statinfer from npm:

npm install statinfer

This JavaScript code reproduces the result above. It also works unchanged in TypeScript, where statinfer's built-in types give you autocompletion and type checking.

import { chiSquareTest, summarize } from "statinfer";

const result = chiSquareTest({
  table: [
    [12, 5],
    [7, 16],
  ],
});

console.log(summarize(result));

For every option chiSquareTest accepts, see its API documentation (opens in a new tab).

The raw result

chiSquareTest returns a plain JavaScript object, which your code can use directly. For example, result.pValue is the p-value. Below, the same object is shown as JSON (JavaScript Object Notation), a standard text format for data, which you can save or send to other programs. A chi-square test has no estimate, confidence interval or direction, so those fields are null.

Show the raw result as JSON
{
  "method": "Chi-square test of independence (Yates' correction)",
  "statistic": 4.812286470652336,
  "pValue": 0.028257528526361268,
  "df": 1,
  "estimate": null,
  "confidenceInterval": null,
  "confidenceLevel": null,
  "alternative": null
}

Further reading