Example R programs and commands
7. Mann-Whitney, Wilcoxon, McNemar, and median comparison tests
# All lines preceded by the "#" character are my comments.
# All lines preceded by the ">" character are my input.
# All other lines are the R program output.
# Mann-Whitney test (special case of Wilcoxon test) comparing made-up
# statistics from two non-normal populations:
> x1 <- c(1.1, 2.1, 1.7, 1.6, 1.9, 1.3)
> x2 <- c(1.0, 1.2, 0.7, 0.6, 0.9, 0.5)
> wilcox.test(x1,x2)
Wilcoxon rank sum test
data: x1 and x2
W = 35, p-value = 0.004329
alternative hypothesis: true location shift is not equal to 0
# Wilcoxon paired-rank test comparing made-up statistics from
# two non-normal populations, with the one-tailed hypothesis
# H_A: x1_k > x2_k + 0.2
#
> x1 <- c(1.1, 2.1, 1.7, 1.6, 1.9, 1.3)
> x2 <- c(1.0, 1.2, 0.7, 0.6, 0.9, 0.5)
wilcox.test(x1,x2, mu=0.2, alternative="greater", paired=TRUE)
Wilcoxon signed rank test with continuity correction
data: x1 and x2
V = 20, p-value = 0.02924
alternative hypothesis: true location shift is greater than 0.2
Warning message:
cannot compute exact p-value with ties in:
wilcox.test.default(x1, x2, mu = 0.2, alternative = "greater",
## NOTE: In R, use
# A <- matrix( c(1,3,2,4), nrow=2, ncol=2)
## to get a 2x2 matrix with columns (1;3) and (2;4), rows (1,2),(3,4).
## Use solve(A) to compute the matrix inverse of a matrix A.
# McNemar's test for independence of two factors, without
# continuity correction:
> table <- matrix(c(33,15,12,65), nrow=2,ncol=2) # 2x2 contingency table
> mcnemar.test(table, correct=FALSE);
McNemar's Chi-squared test
data: table
McNemar's chi-squared = 0.3333, df = 1, p-value = 0.5637
# ... and with continuity correction:
> mcnemar.test(table, correct=TRUE);
McNemar's Chi-squared test with continuity correction
data: table
McNemar's chi-squared = 0.1481, df = 1, p-value = 0.7003
# Median comparison test: count samples above and not above the joint median.
> m <- median(c(x1,x2)) # joint median
> f11 <- sum(x1>m) # Pop.1 samples above median
> f12 <- sum(x2>m)
> f21 <- sum(x1<=m) # Pop.1 samples below or at median
> f22 <- sum(x2<=m)
> table <- matrix(c(f11,f12,f21,f22), nrow=2,ncol=2) # 2x2 contingency table
> chisq.test(table)
Pearson's Chi-squared test with Yates' continuity correction
data: table
X-squared = 3, df = 1, p-value = 0.08326
Warning message:
Chi-squared approximation may be incorrect in: chisq.test(table)