4
$\begingroup$

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?

$\endgroup$
3

2 Answers 2

8
$\begingroup$

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

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 = 
  AssociationThread[
   titanicColumnNames -> Range[Length[titanicColumnNames]]];

Make a contingency matrix

ctCounts = 
  CrossTabulate[
   titanicData[[All, 
     aTitanicColumnNames /@ {"passenger class", "passenger survival"}]]];

MatrixForm[ctCounts]

enter image description here

Make a contingency tensor (using a formula)

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

enter image description here

$\endgroup$
4
$\begingroup$

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

enter image description here

$\endgroup$

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.