[R] Sample all possible contingency tables both margin fixed

David L Carlson dcarlson at tamu.edu
Tue Jun 24 20:18:47 CEST 2014


Since a 2x2 table with fixed row and column margins has only one degree of freedom, it is pretty easy to enumerate them:

   A    B  
A  a    c    M[3]
B  b    d    M[4]
   M[1] M[2]   N

Create a vector of the margins:
M <- c(a+b, c+d, a+c, b+d)

The number of possible tables is min(M[c(1, 3)])+1 since a cannot be larger than the first column margin or the first row margin. The +1 recognizes that a can be 0.

Given any vector M of marginal values, the 2x2 tables are as follows:

M <- c(8, 9, 9, 8) # For example
M[1]+M[2]==M[3]+M[4] # Check to make sure these are valid margins
TRUE
all.2x2s <- t(sapply(0:min(M[c(1,3)]), function(i) c(a=i, b=M[1] - i,
            c=M[3] - i, d=M[4] - M[1] + i)))
all.2x2s
      a b c d
 [1,] 0 8 9 0
 [2,] 1 7 8 1
 [3,] 2 6 7 2
 [4,] 3 5 6 3
 [5,] 4 4 5 4
 [6,] 5 3 4 5
 [7,] 6 2 3 6
 [8,] 7 1 2 7
 [9,] 8 0 1 8

-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352

----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Gabor Grothendieck
Sent: Tuesday, June 24, 2014 12:07 PM
To: Tahira Jamil
Cc: r-help at r-project.org
Subject: Re: [R] Sample all possible contingency tables both margin fixed

On Tue, Jun 24, 2014 at 10:41 AM, Tahira Jamil <tahjamil at gmail.com> wrote:
> Hi,
>
> I am interested in generating all possible contingency table (2 by 2) with fixed row margins and column margins. Can anyone help me.
>

If the reason you want this is to sample them then r2dtable can do
that directly.

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list