到現在為止,我們已經學會了單樣本的正態性檢驗。 而更常用的操作是比較兩個樣本的特徵。在 R 裏面,所有“傳統”的檢驗都放在 包 stats 裏面。這個包常常會自動載入。
下面是冰融化過程的潛熱(latent heat)(cal/gm) 資料(來自 Rice (1995, p.490))
Method A: 79.98 80.04 80.02 80.04 80.03 80.03 80.04 79.97
80.05 80.03 80.02 80.00 80.02
Method B: 80.02 79.94 79.98 79.97 79.97 80.03 79.95 79.97
盒狀圖(boxplot)為這兩組資料提供簡單的圖形比較。
A <- scan()
79.98 80.04 80.02 80.04 80.03 80.03 80.04 79.97
80.05 80.03 80.02 80.00 80.02
B <- scan()
80.02 79.94 79.98 79.97 79.97 80.03 79.95 79.97
boxplot(A, B)
從圖上可以直觀的看出第一組資料 相比第二組資料傾向給出較大的值。
為了比較兩個樣本的均值是否相等,我們可以使用 非配對 t-檢驗
> t.test(A, B)
Welch Two Sample t-test
data: A and B
t = 3.2499, df = 12.027, p-value = 0.00694
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
0.01385526 0.07018320
sample estimates:
mean of x mean of y
80.02077 79.97875
上面的結果表明在正態前提下,二者有明顯的統計差異。
R 函數默認兩個樣本方差不齊,
而 S-Plus 相似函數 t.test
則默認方差齊性。如果兩個樣本都是來自正態群體,
我們可以用F檢驗來確定方差的齊性情況,
> var.test(A, B)
F test to compare two variances
data: A and B
F = 0.5837, num df = 12, denom df = 7, p-value = 0.3938
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
0.1251097 2.1052687
sample estimates:
ratio of variances
0.5837405
這表明二者方差在統計學上沒有顯著差異,我們可以採用傳統的 假設方差齊性的t-檢驗。
> t.test(A, B, var.equal=TRUE)
Two Sample t-test
data: A and B
t = 3.4722, df = 19, p-value = 0.002551
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
0.01669058 0.06734788
sample estimates:
mean of x mean of y
80.02077 79.97875
所有這些檢驗都假設了資料的正態性。雙樣本的 Wilcoxon (或者 Mann-Whitney) 檢驗沒有正態性的前提,僅僅要求 在無效假設情況下樣本來自一個常規的連續分佈。
> wilcox.test(A, B)
Wilcoxon rank sum test with continuity correction
data: A and B
W = 89, p-value = 0.007497
alternative hypothesis: true mu is not equal to 0
Warning message:
Cannot compute exact p-value with ties in: wilcox.test(A, B)
注意警告資訊:在兩個樣本中都有同秩現象。這表明這些資料 來自離散分佈(可能會進行 一定的近似處理)。
有好多種方法可以圖形化的顯示兩個樣本的差別。我們已經 看過盒狀圖的比較。下麵的命令
> plot(ecdf(A), do.points=FALSE, verticals=TRUE, xlim=range(A, B))
> plot(ecdf(B), do.points=FALSE, verticals=TRUE, add=TRUE)
同時顯示兩個樣本的經驗累計概率分佈,而 qqplot 得到的是兩個樣本的
Q-Q 圖。Kolmogorov-Smirnov 檢驗是對兩個經驗累計概率分佈間的最大垂直距離
進行統計的。Kolmogorov-Smirnov 檢驗假定資料服從一個常規的
連續分佈:
> ks.test(A, B)
Two-sample Kolmogorov-Smirnov test
data: A and B
D = 0.5962, p-value = 0.05919
alternative hypothesis: two.sided
Warning message:
cannot compute correct p-values with ties in: ks.test(A, B)