如何使用 R 数据框中的分类列应用两个样本 t 检验?
要使用R数据框中的分类列应用两个样本t检验,我们可以按照以下步骤操作-
首先,创建一个数据框。
然后,使用t.test带有分类列和数字列的函数,用~符号链接。
示例
创建数据框
让我们创建一个数据框,如下所示-
Gender<-sample(c("Male","Female"),30,replace=TRUE) Score<-sample(1:10,30,replace=TRUE) df<-data.frame(Gender,Score) df输出结果
执行时,上述脚本生成以下内容output(thisoutputwillvaryonyoursystemduetorandomization)-
Gender Score 1 Female 5 2 Female 6 3 Male 3 4 Male 7 5 Female 8 6 Female 6 7 Male 10 8 Male 9 9 Male 10 10 Male 6 11 Female 3 12 Male 2 13 Female 7 14 Male 6 15 Male 4 16 Female 5 17 Female 3 18 Female 8 19 Male 1 20 Male 5 21 Male 3 22 Male 1 23 Male 4 24 Female 1 25 Male 6 26 Male 10 27 Female 5 28 Male 2 29 Male 1 30 Male 9
使用分类列执行t检验
使用t.test带有性别列和分数列的函数与~符号链接,如下所示-
Gender<-sample(c("Male","Female"),30,replace=TRUE) Score<-sample(1:10,30,replace=TRUE) df<-data.frame(Gender,Score) t.test(Score~Gender,data=df)输出结果
Welch Two Sample t-test data: Score by Gender t = 1.2604, df = 24.862, p-value = 0.2192 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -0.8460465 3.5127132 sample estimates: mean in group Female mean in group Male 6.166667 4.833333