Create 100 2x2 contingency tables with specified probabilities of each column

I would like to generate a large number of 2x2 contingency tables in r studio, using a specified probability in each column.
If i had an example where a column has title '1', then there would be a 20% chance that a person could be allocated to that row, otherwise, the second row - with a total number of 20 people.

How can i randomly generate these?

Can you provide a reproducible example of your dataset?

The data needs to be randomly generated. For example, we have 20 males who are randomly allocated in either attending or not attending a sporting event (20% chance of attending) and 20 females who are either attending or not attending (20% chance of attending). How could i generate 100 contingency tables of these random occurrences?

I believe i may have to use a for loop

myran <- function(num_males, prob_attend_male,
                  num_fem, prob_attend_fem) {
  mframe <- data.frame(
    M_or_F = rep("M", num_males),
    attend = sample(c(0, 1), 
    size = num_males, 
    prob = c(1 - prob_attend_male, prob_attend_male), replace = TRUE)
  )
  fframe <- data.frame(
    M_or_F = rep("F", num_fem),
    attend = sample(c(0, 1), 
    size = num_fem, 
    prob = c(1 - prob_attend_fem, prob_attend_fem), replace = TRUE)
  )

  together <- rbind(mframe, fframe)

  table(
    together$M_or_F,
    together$attend
  )
}

# once
myran(20,.2,20,.2)

# 100 times  (library(purrr))
purrr::map(1:100,~myran(20,.2,20,.2))

I want to replace this part with the following:

rbinom(num_males, 1, prob_attend_male)

Does the same thing, just in a concise way.

1 Like