# Comparing the proportion of participants in multiple cohorts - chi square?

I've got a data frame featuring participants belonging to one of four cohorts (a,b,c, and d). Every participant was asked about their gender (1=female, 2=male, 3= don't want to answer).

How do I compare the proportion of eg females in the different cohorts (a, b, c, and d)?

I've tried a chi-square test (see below) but I'm not sure about this. I'm interested in the proportion of eg females, and it seems to me I haven't in any way factored in the size of the cohorts.

Any help would be much appreciated!

# Prep data
gender<-floor(runif(240, min=1, max=4))
data_cohort<-rep(c("a", "b","b", "c","d"), 48)
df<-data.frame(data_cohort,gender)

# Get summary stats
library(dplyr)
df2 <- df  %>%
group_by(data_cohort,gender) %>%
summarise (n = n()) %>%
mutate(freq = round((n / sum(n)),2))
df2 <- as.data.frame(df2)

# Run test to compare the proportion of females (gender == 1) in the cohorts
myvec <- df2[df2\$gender == 1, "n"]
chisq.test(myvec)


Your myvec is a vector. chisq.test will conduct a chi-square goodness-of-fit test in this case, with the null hypothesis being that each group has 25% of the females observed.

On the surface this may seem to make sense, but in this case it's particularly meaningless because the total count of individuals across cohorts isn't equal, so you wouldn't expect the count of females to be equal across cohorts.

XT = xtabs(n ~ gender + data_cohort, data=df2)
XT

colSums(XT)

###  a  b  c  d
### 48 96 48 48


I think what you want is to compare the proportion of females in each group relative to the total individuals in that group. For this, you want to use a chi-square test of association where the null hypothesis is that there is no association between gender and cohort.

To get the relevant table, you can use either xtabs with df2 or table with df, as follows.

XT = xtabs(n ~ gender + data_cohort, data=df2)
XT

###        data_cohort
### gender  a  b  c  d
###      1 19 33 13 11
###      2 10 30 18 19
###      3 19 33 17 18

Table = table(df)
Table

###               gender
### data_cohort  1  2  3
###           a 19 10 19
###           b 33 30 33
###           c 13 18 17
###           d 11 19 18

chisq.test(Table)

###   Pearson's Chi-squared test
###
### data:  Table
### X-squared = 6.1162, df = 6, p-value = 0.4103

chisq.test(XT)

###   Pearson's Chi-squared test
###
### data:  Table
### X-squared = 6.1162, df = 6, p-value = 0.4103