2
$\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$
  • 1
    $\begingroup$ A related question. $\endgroup$ – J. M. is away Aug 14 '17 at 16:27
  • $\begingroup$ related question dont help! $\endgroup$ – Mudy Fa Aug 14 '17 at 16:55
  • $\begingroup$ I didn't say there was a solution there, only that it was related. $\endgroup$ – J. M. is away Aug 14 '17 at 17:13
6
$\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$

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.