title: How do I create a random contingency table in R?
body: <p>I would like to create random two-way contingency tables, given fixed row and column marginals.  Supposing I have a table like this:</p>
  
  <pre><code>      A   C   G   T
    A  79   6  13  53
    C  16   7   6  17
    G   9   3   1   6
    T  58  28  18 114
  </code></pre>
  
  <p>with given row marginals:</p>
  
  <pre><code>  A   C   G   T 
  151  46  19 218 
  </code></pre>
  
  <p>and column marginals:</p>
  
  <pre><code>  A   C   G   T 
  162  44  38 190 
  </code></pre>
  
  <p>I'd like to create a random contingency table, for example:</p>
  
  <pre><code>   A  C  G  T
  A 49 16 10 76
  C 23  2  6 15
  G 11  0  1  7
  T 79 26 21 92
  </code></pre>
  
  <p>which preserves those marginals.</p>
  
  <p>Since n is not too large in this case, I tried to approach this by "untabling" the marginal vectors, i.e. by converting the marginals into vectors of the form </p>
  
  <pre><code>A A A ...C C C ... G G G ... T T T 
  </code></pre>
  
  <p>and then permuting and tabling them.</p>
  
  <p>My current method for "untabling" the marginals is highly unnatural and inefficient, and I was curious to know if there's a better way.  Certain built-in functions must create random contingency tables, for instance chisq.test when simulate.p.value=TRUE.  Is random contingency table construction also built in?</p>
  
  <p>Thanks in advance for any suggestions.</p>