# Solved – Cell chi square test

chi-squared-test

I need to do a cell chi square test, but googling availeth me not (I suspect because of all the pages about the cells in chi square discussions generally). How does one calculate this? Any good sources on it, or on it in R specifically?

As @Glen noted in the comments, the cell $\chi^{2}$-test simply calculates a bunch of $\chi^{2}$-tests on the collapsed 2x2 tables. It is fairly easy to implement in R:

# Example table
M <- as.table(rbind(c(762, 327, 468), c(484, 239, 477)))
dimnames(M) <- list(gender = c("M","F"),
party = c("Democrat","Independent", "Republican"))

M
party
gender Democrat Independent Republican
M      762         327        468
F      484         239        477

res.table <- matrix(NA, nrow=dim(M), ncol=dim(M))
dimnames(res.table) <- dimnames(M)

# Loop over all cells of the table

for ( i in 1:dim(M) ) {
for ( j in 1:dim(M) ) {

temp.table <- matrix(NA, 2, 2) # the collapsed 2x2 table

temp.table[1,1] <- M[i,j]
temp.table[1,2] <- sum(M[-i, j], na.rm=TRUE)
temp.table[2,1] <- sum(M[i, -j], na.rm=TRUE)
temp.table[2,2] <- sum(M[-i, -j], na.rm=TRUE)

chi2 <- chisq.test(temp.table, correct=TRUE) # chi2-test with continuity correction

# Automatically choose significance level (see SPSS documentation)

sig.level <- ifelse(M[i,j] <= 300, 0.1,
ifelse(M[i,j] > 300 & M[i,j] <= 1000, 0.05,
ifelse(M[i,j] > 1000 & M[i,j] <= 4000, 0.025,
ifelse(M[i,j] > 4000 & M[i,j] <= 20000,0.005,0.001)
)
)
)

if ( chi2$p.value < sig.level ) { res.table[i, j] <- paste( chi2$observed,
ifelse(chi2$observed < chi2$expected, "<", ">"),
round(chi2\$expected, 2))

} else {

res.table[i, j] <- "n.s."

}
}
}

res.table

party
gender Democrat       Independent Republican
M "762 > 703.67" "n.s."      "468 < 533.68"
F "484 < 542.33" "n.s."      "477 > 411.32"