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)


# once

# 100 times  (library(purrr))

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

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.