Learn R Programming

sensitivityIxJ (version 0.1.5)

possible.table: Generate All Possible Contingency Tables Exceeding or Not Exceeding a Threshold

Description

Given an observed contingency table (with fixed margins) and a user-defined function that computes a test statistic, this function enumerates all valid contingency tables that meet a particular criterion (i.e., those with T(table) >= threshold or T(table) <= threshold).

Usage

possible.table(
  threshold,
  table,
  direction = c("greater than", "less than"),
  transform.fun
)

Value

A list of all contingency tables (each table is returned as a table object) that meet the specified threshold criterion. If no tables match or the dimension is not supported, NULL is returned.

Arguments

threshold

A numeric value representing the cutoff for the test statistic.

table

A matrix or table object specifying the observed contingency table. The function will preserve the row/column sums (margins) of this table when generating possible tables.

direction

A character string, either "greater than" or "less than", indicating whether to return tables whose test statistic is >= threshold or <= threshold. Defaults to c("greater than", "less than") but you should pass in one value explicitly.

transform.fun

A user-defined function of the form f(tbl), which takes a contingency table (as a matrix or table) and returns a numeric test statistic.

Details

The function systematically iterates over all valid ways to fill a contingency table of dimension I x J such that row and column sums match the original table's margins. Only those tables that satisfy transform.fun(tbl) >= threshold (for direction = "greater than") or transform.fun(tbl) <= threshold (for direction = "less than") are returned.

Currently, this function supports certain table dimensions (I up to 5 when J=2, etc.). If the dimension is not supported, it returns NULL with a warning.

Examples

Run this code
# Suppose we have a 3x3 table:
obs_table <- matrix(c(5, 3, 2, 6, 11, 7, 3, 0,3), ncol = 3, byrow = TRUE)
obs_table

# Define a simple test statistic function (e.g., sum of diagonal)
diag_sum <- function(tbl) sum(diag(tbl))

# Find all 3x3 tables with the same margins where the diagonal sum >= 19
result <- possible.table(threshold = 19, table = obs_table,
                        direction = "greater than", transform.fun = diag_sum)
result[[1]]         # Inspect the first matching table

Run the code above in your browser using DataLab