R中的两个样本t检验:比较的方向?

two sample t test in R: direction of comparison?

假设我有吸烟者和非吸烟者的肺活量数据。所以我们有变量 "lungCap" 和数值,变量 "smoking" 有值 "yes" 或 "no"。现在我想看看非吸烟者的容量是否比吸烟者的容量大:

t.test(lungCap~smoking, alt="greater")

如果 "yes" > "no""no" > "yes"[,测试现在是否计算=17=]?这是如何确定的?我在 t.test 命令的帮助中找不到它。

使用基于字符的自变量时,t.test() 将根据自变量中值的字母顺序进行比较。

为了说明这一点,我们将使用 1973 年汽车趋势汽车数据集比较手动和自动变速器汽车的每加仑英里数。

我们将创建一个字符变量来表示自动与手动(以说明 OP 中的场景)和 运行 t 测试。

我们将检验以下假设:

  • H_null: 手动挡车的mpg <= 自动挡车的mpg
  • H_alt: 手动挡汽车的mpg大于自动挡汽车的mpg。

为了 运行 测试,我们将加载数据,创建额外的列并执行 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() 运行s 自动 > 手动,因此 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 示例,如果我们希望手动变速器成为比较中的第一组,以便我们为备选假设 h_alt: mpg(manual) > mpg(automatic) 获得正 t 值,我们可以使用以下代码.

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