sample_2x2 has one row per subject with a row category row_cat ('A' or 'B') and a column category col_cat ('X' or 'Y'). factorials maps an integer n to n! in fact. Build the 2x2 table of cell counts and its margins, then return one row with the probability of observing exactly this table under Fisher's exact test (point_prob) and a flag saying whether Fisher's test is warranted (fisher_warranted).
Name the cells and margins as follows:
| X | Y | Row total |
|---|
| A | a | b | r1 = a + b |
| B | c | d | r2 = c + d |
| Column total | k1 = a + c | k2 = b + d | n = a + b + c + d |
Input Table(s)
sample_2x2
| Column | Type | Meaning |
|---|
| row_cat | VARCHAR(5) | Row category of the subject, 'A' or 'B' |
| col_cat | VARCHAR(5) | Column category of the subject, 'X' or 'Y' |
There is no primary key. Each row is one subject.
factorials
| Column | Type | Meaning |
|---|
| n | INT | A non-negative integer |
| fact | DOUBLE PRECISION | n! |
Primary key: n.
Output Contract
Exactly one row with these columns, in this order:
| Column | Definition |
|---|
| point_prob | (r1! * r2! * k1! * k2!) / (n! * a! * b! * c! * d!), rounded to 6 decimals |
| fisher_warranted | 1 when any of the four expected counts (row total * column total / n) is below 5, else 0 |
The result is a single row, so no ordering applies.
Example
sample_2x2
| row_cat | col_cat |
|---|
| B | Y |
| A | X |
| B | Y |
| B | X |
| A | X |
| A | Y |
| B | X |
| A | X |
| B | Y |
| A | X |
| A | X |
factorials (rows for n 0 to 11 shown; the full table continues to n = 16)
| n | fact |
|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
| 6 | 720 |
| 7 | 5040 |
| 8 | 40320 |
| 9 | 362880 |
| 10 | 3628800 |
| 11 | 39916800 |
Expected result:
| point_prob | fisher_warranted |
|---|
| 0.181818 | 1 |
The cells are a = 5, b = 1, c = 2 and d = 3, so r1 = 6, r2 = 5, k1 = 7, k2 = 4 and n = 11. The expected count for cell (A, X) is 6 * 7 / 11, about 3.82, which is below 5.
Constraints and Clarifications
-
row_cat
is always
'A'
or
'B'
and
col_cat
is always
'X'
or
'Y'
. Neither column is NULL.
-
sample_2x2
has at least one row.
-
A cell, or a whole row or column, can be empty. Its count is 0, and 0! = 1.
-
factorials
has a row for every integer from 0 up to the number of rows in
sample_2x2
.
-
Identical rows in
sample_2x2
are different subjects and each one counts.
-
An expected count of exactly 5 does not set the flag (the comparison is strictly below 5).