Source: http://www.r-bloggers.com/two-sample-students-t-test-1/
t-Test用来比较两个群组的均值,这里假设两个样本组都随机、独立,并且来自方差未知但相等的正态分布的总体。
这里我们使用和《两个样本的Z-test》中一样的数据,如下:
A: 175, 168, 168, 190, 156, 181, 182, 175, 174, 179
B: 185, 169, 173, 173, 188, 186, 175, 174, 179, 180
为解决这个问题,我们必须使用针对两个样本的Student's t-test,这里假设这两个样本取自符合Gaussian分布的总体(如果我们不能够假设这个条件,我们必须使用称作Wilcoxon-Mann-Whitney test的non-parametric test来解决这个问题)。在进行t-test之前,有必要两个群组的的样本方差,这里使用Fisher's F-test来检验homoskedasticity。在R中你可以照着以下做:
a = c(175, 168, 168, 190, 156, 181, 182, 175, 174, 179) b = c(185, 169, 173, 173, 188, 186, 175, 174, 179, 180) var.test(a,b) F test to compare two variances data: a and b F = 2.1028, num df = 9, denom df = 9, p-value = 0.2834 alternative hypothesis: true ratio of variances is not equal to 1 95 percent confidence interval: 0.5223017 8.4657950 sample estimates: ratio of variances 2.102784
我们获得的p-value大于0.05,因此我们可以假设两个方差是同质的(homogeneous)。实际上我们能用获得的F值与查表的F值比较(查表时取alpha=0.05,分子自由度=9,分母自由度=9),R中用函数qf(p, df.num, df.den)获得:
qf(0.95, 9, 9) [1] 3.178893
注意到前面计算的F值小于这里的查表F值,于是我们接受方差同质的null hypothesis。注意:F分布只有单尾,因此对95%的置信区间,取p=0.95。相反地,t分布有双尾,在函数qt(p, df)中需要设值p=0.975。
接下来就调用函数t.test,并设同质方差(var.equal = TRUE)和独立样本(paired = FALSE:函数默认取值,可省略),如下:
t.test(a,b, var.equal=TRUE, paired=FALSE) Two Sample t-test data: a and b t = -0.9474, df = 18, p-value = 0.356 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -10.93994 4.13994 sample estimates: mean of x mean of y 174.8 178.2
我们获得的p-value大于0.05,于是我们论断两个群组的平均显著相似。实际上计算的t值小于查表的自由度为18的t值,在R中如下得到:
qt(0.975, 18) [1] 2.100922
这确认我们能接受均值相等的null hypothesis H0。