r2dtable                package:stats                R Documentation

_R_a_n_d_o_m _2-_w_a_y _T_a_b_l_e_s _w_i_t_h _G_i_v_e_n _M_a_r_g_i_n_a_l_s

_D_e_s_c_r_i_p_t_i_o_n:

     Generate random 2-way tables with given marginals using
     Patefield's algorithm.

_U_s_a_g_e:

     r2dtable(n, r, c)

_A_r_g_u_m_e_n_t_s:

       n: a non-negative numeric giving the number of tables to be
          drawn.

       r: a non-negative vector of length at least 2 giving the row
          totals, to be coerced to 'integer'.  Must sum to the same as
          'c'.

       c: a non-negative vector of length at least 2 giving the column
          totals, to be coerced to 'integer'.

_V_a_l_u_e:

     A list of length 'n' containing the generated tables as its
     components.

_R_e_f_e_r_e_n_c_e_s:

     Patefield, W. M. (1981) Algorithm AS159.  An efficient method of
     generating r x c tables with given row and column totals. _Applied
     Statistics_ *30*, 91-97.

_E_x_a_m_p_l_e_s:

     ## Fisher's Tea Drinker data.
     TeaTasting <-
     matrix(c(3, 1, 1, 3),
            nrow = 2,
            dimnames = list(Guess = c("Milk", "Tea"),
                            Truth = c("Milk", "Tea")))
     ## Simulate permutation test for independence based on the maximum
     ## Pearson residuals (rather than their sum).
     rowTotals <- rowSums(TeaTasting)
     colTotals <- colSums(TeaTasting)
     nOfCases <- sum(rowTotals)
     expected <- outer(rowTotals, colTotals, "*") / nOfCases
     maxSqResid <- function(x) max((x - expected) ^ 2 / expected)
     simMaxSqResid <-
         sapply(r2dtable(1000, rowTotals, colTotals), maxSqResid)
     sum(simMaxSqResid >= maxSqResid(TeaTasting)) / 1000
     ## Fisher's exact test gives p = 0.4857 ...

