I have a factor variable with two levels that represent a patient's baseline condition. I have separated these patients into two groups based on another variable - these two groups do not have the same number of patients in them.

Using a chi-squared test, I want to compare the distribution of this baseline condition between the two groups of patients.

How would this be done in R?

  • $\begingroup$ It sounds like you have four groups, not two. Could you please clarify? $\endgroup$
    – Dave
    Commented Oct 11, 2022 at 0:17
  • $\begingroup$ @Dave group 1: major operation or light procedure, group 2: major operation or light procedure; I want to see what the difference in distribution is for the two groups $\endgroup$
    – amatof
    Commented Oct 11, 2022 at 0:32
  • $\begingroup$ @Dave but whether a patient had a major operation or a light procedure is stored in one variable (called baseline) $\endgroup$
    – amatof
    Commented Oct 11, 2022 at 0:50
  • 2
    $\begingroup$ ?chisq.test .. $\endgroup$
    – Glen_b
    Commented Oct 11, 2022 at 6:26

1 Answer 1


To test for the presence of association between two factors through the associated contingency table, you have a bunch of possibilities, below are two of the most popular options:

  1. If the sample size is small it is advisable to use Fisher's exact test which provides an exact $p$-value. It is implemented in the R command fisher.test

  2. With large samples you may use a chi-squared test or the G-test. The $p$-values provided by these tests are approximate since the sampling distribution of the test statistic is a chi-squared only in the limit as the sample size goes to infinity. The approximation is particularly inadequate when sample sizes are small, or the expected counts under the null hypothesis are very low. As suggested by @Glen_b, you can run the chi-squared test in R by the command chisq.test; implementation of the G-test is provided by the command g.test in the ARM package.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.