I am working on a very large dataset of patients who belong to one of five groups. I want to test if groups are not so much different than each other in terms of age, race, sex, smoking level, weight, and some other factors. Some factors are numerical and some are categorical. I know I can use ANOVA to compare mean differences between groups for numerical factors. However, I do not know how I can test mean differences for categorical factors. Some references say that Chi-Squared test can be used for this purpose, but it seems that chisq.test in R is only for testing either independency or goodness of fit.

Could someone write a sample code in R showing how the mean differences between more than two groups can be evaluated for a categorical factor? Is any pre-evaluation required to check if a specific test is valid to be used? Thanks in advance.

  • 2
    $\begingroup$ What is the mean of a categorical variable? $\endgroup$ Feb 17, 2014 at 17:02
  • $\begingroup$ What you want is precisely a Chi-sq test of independence $\endgroup$ Feb 17, 2014 at 17:11
  • $\begingroup$ @JuliánUrbano, is really a Chi-sq test of independence correct for comparing the means? Even if the answer is Yes, how multiple groups can be compared all at one, not just two by two each time? $\endgroup$ Feb 17, 2014 at 17:19

1 Answer 1


First of all, there is no such thing as the mean when you have a categorical variable. So you cannot compare means across groups, it doesn't make sense. What you can do is compare their distributions, that is, whether the distribution for one group is the same as another.

For that you do want a Chi-square test of independence, to test whether your dependent variable is independent of your independent variable. In other words, that knowing the group of your patient does not provide you with any kind of information to predict the distribution of the dependent variable (and they all come from the same distribution).

Here is an example were the independent variable x is one of five patient groups, and the dependent variable y tells whether the patient smokes or not. Group 5 has a different distribution than the others.

> set.seed(1234)
> y <- factor(c(sample(0:1,size=40,replace=T),
> x <- factor(rep(1:5,each=10),
> t <- table(x,y)
> t
x    yes no
  g1   3  7
  g2   6  4
  g3   6  4
  g4   6  4
  g5   0 10
> chisq.test(t)

        Pearson's Chi-squared test

data:  t
X-squared = 11.8227, df = 4, p-value = 0.01872

Mensajes de aviso perdidos
In chisq.test(t) : Chi-squared approximation may be incorrect

Your Answer

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

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