# Creating a contingency table

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?

• A related question. Aug 14, 2017 at 16:27
• related question dont help! Aug 14, 2017 at 16:55
• I didn't say there was a solution there, only that it was related. Aug 14, 2017 at 17:13

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

Import["https://raw.githubusercontent.com/antononcube/MathematicaForPrediction/master/CrossTabulate.m"]


### 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 =
CrossTabulate[
titanicData[[All,
aTitanicColumnNames /@ {"passenger class", "passenger survival"}]]];

MatrixForm[ctCounts]


### Make a contingency tensor (using a formula)

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


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