DEV Community

Jaye Ross
Jaye Ross

Posted on

How to convert 2x2 contingency tables into a format the infer package can use

Suppose you have this data (from http://www.feat.engineering/stroke-tour):

data = c(43, 39, 19, 25)
Enter fullscreen mode Exit fullscreen mode

Suppose you want to perform a Chi-squared test of association. In base R, you can do this:

data |>
matrix(nrow=2) |>
chisq.test()
Enter fullscreen mode Exit fullscreen mode

However, suppose you want to use the infer package. Unlike chisq.test, you cannot provide the contingency table directly. In order to use the package, you can convert the table into the appropriate format like this. The idea is to first create the combinations of the factors and then use uncount to produce the correct format:

expand.grid(
  stroke = factor(c(1,0)),
  blockage = factor(c(1,0))
) |>
bind_cols(value = data) |>
uncount(value) |>
chisq_test(stroke ~ blockage)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)