如何对 R 数据框的每一行应用 t 检验?
要对R数据帧的每一行应用ttest,我们可以使用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检验
对于OneSamplet-test,在上面创建的数据框中,将相应的代码添加到上面的代码片段中-
[[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