### Kruskal-Wallis Test in R: ### Example 1: # If the data are given all in one vector, # with a separate vector of group labels: wtgain<-c(159,115,182,116,264,56,83,132,164,55,225,100,114,76,291,126,132,32,225,209,153,194,270,108,214,264,108,300,332,181,137,249,230,280,162,239,158,155,198,164,283,197,223) diet <- c(rep(1,times=14),rep(2,times=10),rep(3,times=10),rep(4,times=9)) kruskal.test(wtgain ~ diet) # Or the data might be given in k vectors (one for each group): wtgain1 <- wtgain[diet==1] wtgain2 <- wtgain[diet==2] wtgain3 <- wtgain[diet==3] wtgain4 <- wtgain[diet==4] # Then the data vectors are entered as a list, separated by commas: kruskal.test(list(wtgain1, wtgain2, wtgain3, wtgain4)) ###### ## Multiple Comparisons: # Distribution-free Multiple Comparisons in R # Getting the ranks for the data: wtranks <- rank(wtgain) # Printing the ranks for the data: cbind(diet, wtgain, wtranks) # Performing the Multiple Comparisons: group.mean.ranks <- tapply(wtranks,diet,mean) inv.group.sizes <- 1/tapply(wtranks,diet,length) # Getting the pairwise differences in sample mean ranks: outer(group.mean.ranks,group.mean.ranks,'-') # Determining which pairs of treatments are significantly different # Some needed quantities: alpha <- 0.05 N <- length(wtgain) # size of combined sample k <- 4 # number of populations T <- kruskal.test(wtgain ~ diet)$statistic s.sq <- N*(N+1)/12 # cutoff value for multiple comparisons: cutoff <- qt(1-alpha/2,df=N-k)*sqrt(s.sq*(N-1-T)/(N-k)) abs(outer(group.mean.ranks,group.mean.ranks,'-'))/sqrt(outer(inv.group.sizes,inv.group.sizes,'+')) > cutoff ### Which pairs of populations appear to be different? ### Does this match what we see graphically? boxplot(wtgain~diet) ############################################################# ### Example 2: ## Converting the contingency table counts of A,B,C,D,F into raw data vectors of 4,3,2,1,0: instr1 <- rep(4:0, times=c(4,14,17,6,2)) instr2 <- rep(4:0, times=c(10,6,9,7,6)) instr3 <- rep(4:0, times=c(6,7,8,6,1)) kruskal.test(list(instr1, instr2, instr3))