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 ...