################################ # # Section 4.4 R examples # ################################ ## Cramer's Coefficient # Copy and paste this function first: CramerV <- function(xtable){ V<-sqrt(chisq.test(xtable, correct = FALSE)$statistic / (sum(xtable) * min(dim(xtable) - 1 ))) names(V) <- NULL return(V) } # Example 1: test.score.data <- matrix(c(6,14,17,9,30,32,17,3), nrow=2, ncol=4, byrow=TRUE, dimnames = list(c("Private", "Public"), c("Low", "Marginal", "Good", "Excellent"))) CramerV(test.score.data) # Example 2: snore.heart.data <- matrix(c(24,35,51,1355,603,416), nrow=2, ncol=3, byrow=TRUE, dimnames = list(c("Yes", "No"), c("Never", "Occasionally", "~ Every Night"))) CramerV(snore.heart.data) ## Phi coefficient: # Copy and paste this function first: Phi <- function(xtable){ phii<-(xtable[1,1]*xtable[2,2]-xtable[1,2]*xtable[2,1])/sqrt(prod(apply(xtable,1,sum),apply(xtable,2,sum)) ) names(phii) <- NULL return(phii) } # Example 3: Table223A <- matrix(c(28,0,5,7), nrow=2, ncol=2, byrow=TRUE, dimnames = list(c("DarkM", "LightM"), c("DarkF","LightF"))) Phi(Table223A) Table223B <- matrix(c(21,7,12,0), nrow=2, ncol=2, byrow=TRUE, dimnames = list(c("DarkM", "LightM"), c("DarkF","LightF"))) Phi(Table223B) Table223C <- matrix(c(23,5,10,2), nrow=2, ncol=2, byrow=TRUE, dimnames = list(c("DarkM", "LightM"), c("DarkF","LightF"))) Phi(Table223C) # Example 4: haireye22 <- matrix(c(1168,1130,573,2512), nrow=2, ncol=2, byrow=TRUE, dimnames = list(c("LightE", "DarkE"), c("LightH","DarkH"))) as.table(haireye22) Phi(haireye22) ################################ # # Section 4.6 R examples # ################################ ## Cochran's Test: Cochran.Test <- function(xtable){ c <- ncol(xtable) r <- nrow(xtable) N <- sum(xtable) test.stat <- (c*(c-1)*sum(apply(xtable,2,sum)^2) - (c-1)*N*N)/(c*N-sum(apply(xtable,1,sum)^2)) p.value <- pchisq(test.stat, df=(c-1), lower=F) out <-list(test.stat,p.value) return(out) } climbs<-matrix(c(1,1,0, 1,0,1, 0,0,1, 0,1,1, 1,0,1) ,nrow=5,ncol=3,byrow=T) Cochran.Test(climbs)