I need help in creating a function for a contingency table... I imagined to create it like this...

Contingency[a_] := 
 Module[{n = Dimensions[a][[1]], m = Dimensions[a][[2]], ...},

a is a $n \times m$ matrix with frequency distribution.

Is this kinda way possible?


2 Answers 2


Links to implementations

See the bottom of this package, CrossTabulate.m for different implementations (CrossTabulate):

  • one is based on Tally, GatherBy, and SparseArray,

  • the other is based in R' xtabs (via RLink).

The function CrossTensorate generalizes the contingency value finding.

The making of contingency matrices and tensors with those functions is discussed in these posts:

Here is an alternative implementation at Stack Overflow by Mr.Wizard.

Code to try

Get package


Get data

titanicData = 
  Flatten@*List @@@ 
   ExampleData[{"MachineLearning", "Titanic"}, "Data"];
titanicData = DeleteCases[titanicData, {___, _Missing, ___}];

titanicColumnNames = 
  Flatten@*List @@ 
   ExampleData[{"MachineLearning", "Titanic"}, "VariableDescriptions"];
aTitanicColumnNames = 
   titanicColumnNames -> Range[Length[titanicColumnNames]]];

Make a contingency matrix

ctCounts = 
     aTitanicColumnNames /@ {"passenger class", "passenger survival"}]]];


enter image description here

Make a contingency tensor (using a formula)

ctRes = CrossTensorate[
   Count == 
    "passenger survival" + "passenger sex" + "passenger class", 
   titanicData, aTitanicColumnNames];

enter image description here


There is a function in Wolfram Function Repository for making contingency tables: CrossTabulate.

enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.