I have a dataset like this:

enter image description here

All these social determinants are binary variable. How can I find the correlation among them? By chisq.test? Since I have 11 variables and it will be 55 pairs. Is there any convenient way to do so?

R code, function, logic

  • 2
    $\begingroup$ Correlation is defined for continuous variables, not binary variables. What is your research question? Food score does not look binary. $\endgroup$ Sep 20, 2023 at 6:42
  • $\begingroup$ Maybe start with contingency tables? $\endgroup$
    – Roland
    Sep 20, 2023 at 6:54
  • $\begingroup$ Perhaps an interesting read for you "BayesBinMix: an R Package for Model Based Clustering of Multivariate Binary Data" journal.r-project.org/archive/2017/RJ-2017-022/RJ-2017-022.pdf $\endgroup$
    – Merijn van Tilborg
    Sep 20, 2023 at 7:44
  • 1
    $\begingroup$ What are you actually trying to do? Correlations isn't it, but I don't know what is. Explain it to us in substantive terms. $\endgroup$
    – Peter Flom
    Sep 20, 2023 at 11:26
  • $\begingroup$ You can feed your binary matrix with $k$ columns to cor and get a $k\times k$ correlation matrix out, MM <- matrix(runif(10*100)<0.3,ncol=10)+0; cor(MM). Of course correlations are defined for binary variables - they are just probably useless. So I agree with the other commenters that it might be best if you told us what you are actually trying to achieve. $\endgroup$ Sep 20, 2023 at 11:30

2 Answers 2


If your question can be understood has "how to apply a comparison function to every pair of columns in a data.frame" then I would suggest the following:

df <- replicate(5, sample(0:1, 10, T)) |>
  as.data.frame() |>
  setNames(c("skip.med", "stable.housing", "utility.bills", "legal.issues", "addiction"))

comps <- combn(colnames(df),2) |>
colnames(comps) <- sapply(comps, \(x) paste(x[[1]],"-",x[[2]]))

lapply(comps,\(x) {
  chisq.test(df[[x[[1]]]], df[[x[[2]]]])

As suggested in the comments to your question, chisq.test may not be the best option, but you can easily change the function used within the lapply call.


I suggest going back to basics and using a measure that is tailored to binary responses. If two binary responses $A, B$ are independent then $\Pr(A=a, B=b) = \Pr(A=a)\times \Pr(B=b)$. You can use $\Pr(A=1,B=1) - \Pr(A=1)\times\Pr(B=1)$ as a measure of dependence of $A$ and $B$. This is estimated by computing the average product of the binary responses minus the product of the averages. This is like the numerator of a Pearson correlation coefficient.

This is implemented in the R Hmisc package varclus function - see similarity='bothpos' or 'ccbothpos, the latter being what I described above. You can print the similarity matrix and varclus uses it to cluster the variables.


Your Answer

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