Here is another approach. First set up the master table:
tbl <- as.matrix(df[, -1])
Sums <- matrix(colSums(tbl), nrow(tbl), 2, byrow=TRUE)
Tbl <- cbind(tbl, Sums-tbl)
row.names(Tbl) <- df[, 1]
Tbl
# Yes No Yes No
# Asian 584 24 12285 435
# Black 1721 56 11148 403
# Hispanic 2400 90 10469 369
# White 8164 289 4705 170
Now a function to create 2x2 tables from a row in Tbl
:
ChiSqTable <- function(row) {
matrix(Tbl[row, ], 2, 2, byrow=TRUE, dimnames=list(Race=c(df[row, 1],
paste("Not", df[row, 1])), Question=c("Yes", "No")))
}
Finally create Chi Square tables and run the test:
Tables <- lapply(seq(nrow(Tbl)), ChiSqTable)
names(Tables) <- df[, 1]
ChiSqStats <- lapply(Tables, chisq.test)
names(ChiSqStats) <- df[, 1]
Tables[[1]] # or Tables[["Asian"]]
# Question
# Race Yes No
# Asian 584 24
# Not Asian 12285 435
ChiSqStats[[1]]
#
# Pearson's Chi-squared test with Yates' continuity correction
#
# data: X[[i]]
# X-squared = 0.33997, df = 1, p-value = 0.5598
Access the remaining tables, statistical results by specifying the number or Race. All of the results of the Chi Square Test are saved, e.g.
ChiSqStats[[1]]$expected
# Question
# Race Yes No
# Asian 587.0612 20.93878
# Not Asian 12281.9388 438.06122
ChiSqStats[[1]]$residuals
# Question
# Race Yes No
# Asian -0.12634367 0.6689899
# Not Asian 0.02762242 -0.1462607