假设我有吸烟者和非吸烟者的肺活量数据。所以我们有一个带有数值的变量“lungCap”,以及带有“yes”或“no”值的变量“Smoking”。现在我想看看非吸烟者的容量是否大于吸烟者:
t.test(lungCap~smoking, alt="greater")
现在测试是否计算"yes" > "no"或"no" > "yes"?这是如何确定的?我在 t.test 命令的帮助中找不到它。
假设我有吸烟者和非吸烟者的肺活量数据。所以我们有一个带有数值的变量“lungCap”,以及带有“yes”或“no”值的变量“Smoking”。现在我想看看非吸烟者的容量是否大于吸烟者:
t.test(lungCap~smoking, alt="greater")
现在测试是否计算"yes" > "no"或"no" > "yes"?这是如何确定的?我在 t.test 命令的帮助中找不到它。
当使用基于字符的自变量时,t.test()
将根据自变量中值的字母顺序进行比较。
为了说明,我们将使用 1973 Motor Trend 汽车数据集比较手动变速箱与自动变速箱汽车的每加仑英里数。
我们将创建一个字符变量来表示自动与手动(以说明 OP 中的场景)并在测试中运行。
我们将检验以下假设:
为了运行测试,我们将加载数据,创建额外的列并执行t.test()
。
data(mtcars)
mtcars$trans <- ifelse(mtcars$am == 1,"manual","automatic")
t.test(mtcars$mpg ~ mtcars$trans,alt="greater")
...和输出:
> t.test(mtcars$mpg ~ mtcars$trans,alt="greater")
Welch Two Sample t-test
data: mtcars$mpg by mtcars$trans
t = -3.7671, df = 18.332, p-value = 0.9993
alternative hypothesis: true difference in means is greater than 0
95 percent confidence interval:
-10.57662 Inf
sample estimates:
mean in group automatic mean in group manual
17.14737 24.39231
我们在这里看到的是t.test()
自动 > 手动运行,因此 p 值为 0.9993。
为了正确运行测试,我们将对其进行修改以使用该alt="less"
参数。
> t.test(mtcars$mpg ~ mtcars$trans,alt="less")
Welch Two Sample t-test
data: mtcars$mpg by mtcars$trans
t = -3.7671, df = 18.332, p-value = 0.0006868
alternative hypothesis: true difference in means is less than 0
95 percent confidence interval:
-Inf -3.913256
sample estimates:
mean in group automatic mean in group manual
17.14737 24.39231
>
在这里,我们看到报告的 p 值为 0.0006,这意味着我们拒绝原假设,支持替代假设,即自动变速箱汽车的平均每加仑英里数低于手动变速箱汽车。
针对评论中关于是否可以更改分组顺序的问题,该t.test()
功能没有提供执行此操作的方法。但是,可以简单地在组名称前添加1.
和2.
,以强制t.test()
使用包含1.
的组作为比较中的第一个组。
回到我们的mtcars
示例,如果我们希望手动变速器成为比较中的第一组,因此我们可以为备择假设得到一个正的 t 值,h_alt: mpg(manual) > mpg(automatic)
我们可以使用以下代码。
data(mtcars)
mtcars$trans <- ifelse(mtcars$am == 1,"1. manual","2. automatic")
t.test(mtcars$mpg ~ mtcars$trans,alt="greater")
...和输出:
> t.test(mtcars$mpg ~ mtcars$trans,alt="greater")
Welch Two Sample t-test
data: mtcars$mpg by mtcars$trans
t = 3.7671, df = 18.332, p-value = 0.0006868
alternative hypothesis: true difference in means between group 1. manual and group 2. automatic is greater than 0
95 percent confidence interval:
3.913256 Inf
sample estimates:
mean in group 1. manual mean in group 2. automatic
24.39231 17.14737