如何在R中使用数据框中的因子列执行配对t检验?
当我们在R数据框中有一个具有两个水平的因子列和一个数值列时,我们可以对该数据框应用配对t检验,但数据必须是针对同一对象收集的,否则它就不是配对数据。此处讨论的数据的t.test应用可以使用命令t.test(y1~x1,data=df)完成,其中y1是数值列,x1是因子列,这两个列都存储在名为df的数据框中。
示例
考虑以下数据框:
x1<-sample(c("Male","Female"),20,replace=TRUE) y1<-rpois(20,5) df1<-data.frame(x1,y1) df1
输出
x1 y1 1 Female 4 2 Male 4 3 Female 4 4 Male 4 5 Female 6 6 Male 4 7 Female 3 8 Male 4 9 Female 7 10 Male 6 11 Male 2 12 Female 1 13 Male 5 14 Male 8 15 Male 6 16 Male 6 17 Female 3 18 Female 5 19 Male 4 20 Male 5
对df1中的数据应用t.test:
示例
t.test(y1~x1,data=df1)
输出
Welch Two Sample t-test data: y1 by x1 t = -0.88636, df = 12.897, p-value = 0.3917 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -2.436194 1.019527 sample estimates: mean in group Female mean in group Male 4.125000 4.833333
示例
x2<-sample(c("Hot","Cold"),20,replace=TRUE) y2<-sample(0:9,20,replace=TRUE) df2<-data.frame(x2,y2) df2
输出
x2 y2 1 Hot 8 2 Cold 1 3 Hot 5 4 Hot 2 5 Cold 4 6 Cold 0 7 Hot 8 8 Cold 3 9 Cold 9 10 Cold 6 11 Cold 0 12 Cold 9 13 Hot 6 14 Hot 2 15 Cold 3 16 Hot 1 17 Cold 6 18 Hot 7 19 Hot 8 20 Hot 9
对df2中的数据应用t.test:
示例
t.test(y2~x2,data=df2)
输出
Welch Two Sample t-test data: y2 by x2 t = -1.0627, df = 17.721, p-value = 0.3022 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -4.46872 1.46872 sample estimates: mean in group Cold mean in group Hot 4.1 5.6
广告