title: Perform multiple chi-squared test on dataframe based on column value
body: <p>I have a data frame with count numbers and I want to perform a <code>chisq.test</code> for each value of the variable Cluster. So basically, I need 4 contingency tables (for &quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;) where rows = Category, columns = Drug, value = Total. And subsequently a <code>chisq.test</code> should be run for all 4 tabels.</p>
  <p>Example data frame</p>
  <pre><code>df &lt;- data.frame(Cluster = c(rep(&quot;A&quot;,8),rep(&quot;B&quot;,8),rep(&quot;C&quot;,8),rep(&quot;D&quot;,8)),
                   Category = rep(c(rep(&quot;0-1&quot;,2),rep(&quot;2-4&quot;,2),rep(&quot;5-12&quot;,2),rep(&quot;&gt;12&quot;,2)),2),
                   Drug = rep(c(&quot;drug X&quot;,&quot;drug Y&quot;),16),
                   Total = as.numeric(sample(20:200,32,replace=TRUE)))
  </code></pre>