[R] Getting all possible contingency tables

Ben Bolker bbolker at gmail.com
Sat Dec 1 17:13:17 CET 2012


> > 
> > My goal is to generate all possible contingency tables. Basically I want
> > to see the distribution of Chi-squared Statistic under independence
> > (NULL).
> > 
> > So I was thinking if I can generate all possible permutation of integer
> > numbers having sum equal to (8 + 10 + 12 + 6) = 36. Is there any R
> > function to do that?

  I think R *can* do this (thanks to Robin Hankin):

  library(partitions)
  str(parts(36))
 'partition' int [1:36, 1:17977] 36 0 0 0 0 0 0 0 0 0 ...

I'm not quite clear on how you're going to take these results
and turn them into possible tables, but I guess you do ...
You might also be interested in the simulate.p.value option to
chisq.test and the randomizer (which preserves row and column
totals): from the code of chisq.test,

           tmp <- .Call(C_chisq_sim, sr, sc, B, E)


> >>> -----Original Message-----
> >>> From: bogaso.christofer <at> gmail.com

> >>> Let say I have 2-way contingency table:
> >>> 
> >>> Tab <- matrix(c(8, 10, 12, 6), nr = 2)
> >>> 
> >>> and the Chi-squared test could not reject the independence:
> >>> 
> >>>   > chisq.test(Tab)
> >>> 
> >>>           Pearson's Chi-squared test with Yates' continuity correction
> >>> 
> >>> data:  Tab
> >>> X-squared = 1.0125, df = 1, p-value = 0.3143
> >>> 
> >>> 
> >>> However I want to get all possible contingency tables under this
> >>> independence scenario (one of them would obviously be the given table
> >>> as, we could not reject the independence), and for each such table I
> >>> want to calculate the Ch-sq statistic.
> >>> 
> >>> Can somebody help me how to generate all such tables?




More information about the R-help mailing list