如何在 R 数据框的每一行上应用 t 检验?
要对 R 数据框的每一行应用 t 检验,我们可使用 apply 函数及 t.test 函数。例如,我们有一个名为 DF 的数据框,并希望对 DF 的每一行应用 t 检验,则可以使用以下给出的命令 -
apply(DF,1,t.test)
请查看以下示例以了解其工作原理。
示例
下列代码创建一个示例数据框 -
x<-rpois(10,5) y<-rpois(10,2) z<-rpois(10,1) a<-rpois(10,2) b<-rpois(10,5) df<-data.frame(x,y,z,a,b) df
创建了以下数据框
x y z a b 1 2 4 0 2 2 2 8 3 1 4 7 3 6 0 2 3 7 4 6 4 2 1 6 5 6 2 2 3 5 6 5 1 1 4 2 7 6 2 0 3 10 8 3 1 2 2 3 9 7 1 3 4 3 10 5 0 1 0 5
要对 R 数据框的每一行应用 t 检验,请向上述代码段添加以下代码 -
x<-rpois(10,5) y<-rpois(10,2) z<-rpois(10,1) a<-rpois(10,2) b<-rpois(10,5) df<-data.frame(x,y,z,a,b) apply(df,1,t.test)
单个样本 t 检验
对于上述创建的数据框的单个样本 t 检验,请向上述代码段添加相应代码 -
[[1]] One Sample t-test data: newX[, i] t = 3.1623, df = 4, p-value = 0.03411 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: 0.2440219 3.7559781 sample estimates: mean of x 2 [[2]] One Sample t-test data: newX[, i] t = 3.5703, df = 4, p-value = 0.02337 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: 1.022801 8.177199 sample estimates: mean of x 4.6 [[3]] One Sample t-test data: newX[, i] t = 2.7941, df = 4, p-value = 0.0491 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: 0.02280072 7.17719928 sample estimates: mean of x 3.6 [[4]] One Sample t-test data: newX[, i] t = 3.7262, df = 4, p-value = 0.02036 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: 0.9685704 6.6314296 sample estimates: mean of x 3.8 [[5]] One Sample t-test data: newX[, i] t = 4.4313, df = 4, p-value = 0.01141 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: 1.344405 5.855595 sample estimates: mean of x 3.6 [[6]] One Sample t-test data: newX[, i] t = 3.2004, df = 4, p-value = 0.03289 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: 0.3444053 4.8555947 sample estimates: mean of x 2.6 [[7]] One Sample t-test data: newX[, i] t = 2.4089, df = 4, p-value = 0.07365 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: -0.6408975 9.0408975 sample estimates: mean of x 4.2 [[8]] One Sample t-test data: newX[, i] t = 5.8797, df = 4, p-value = 0.004181 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: 1.161149 3.238851 sample estimates: mean of x 2.2 [[9]] One Sample t-test data: newX[, i] t = 3.6742, df = 4, p-value = 0.02131 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: 0.8796505 6.3203495 sample estimates: mean of x 3.6 [[10]] One Sample t-test data: newX[, i] t = 1.9005, df = 4, p-value = 0.1302 alternative hypothesis: true mean is not equal to 0 95 percent confidence interval: -1.013968 5.413968 sample estimates: mean of x 2.2
广告