如何在R数据帧的所有列上应用一个样本t检验?

当我们想对数据帧的列进行t检验时,通常我们通过访问适当的列来逐一执行它们,但是如果我们想对数据帧的所有列进行t检验,那么我们可以借助sapply功能。例如,如果我们有一个名为df的数据框,其中包含多列,则可以使用命令sapply(df,t.test)将一个样本测试应用于所有列。

例1

考虑以下数据帧-

> x1<-rnorm(20)
> x2<-rnorm(20,5,2.5)
> x3<-rnorm(20,5,0.31)
> df1<-data.frame(x1,x2,x3)
> df1
输出结果
            x1        x2       x3
1  -2.25470472  2.730284 5.257561
2   0.31811059  4.978190 4.799871
3   0.53974937  5.247124 4.533089
4   0.04855004  4.285427 5.187038
5   0.23913269  6.424229 5.335241
6   1.41318324  5.184035 5.638625
7  -1.19378598  0.729062 5.065400
8   0.53453582 10.548991 4.349061
9  -0.90284652  2.019270 5.479600
10 -1.85263184  5.272444 5.148048
11  0.20052589  7.367680 4.806746
12 -0.67952841  7.784398 4.908527
13  1.34338527  4.627357 5.090057
14  0.50015711  3.983630 4.370341
15  1.77264005  3.099567 4.930903
16 -0.55921578 -1.081910 5.597464
17 -0.46257623  4.273301 5.045864
18  0.97870030  6.683427 5.051728
19 -0.96029384 10.277885 4.978401
20 -1.33514505  5.534050 4.558999

在df1的所有列上应用t检验-

> sapply(df1,t.test)
输出结果
                  x1                  x2                  x3                
statistic   -0.4687486          7.892499            60.87446          
parameter   19                  19                  19                
p.value     0.6445828           2.047736e-07        3.024457e-23      
conf.int    Numeric,2           Numeric,2           Numeric,2        
estimate    -0.1156029          4.998422            5.006628          
null.value  0                   0                   0                
stderr      0.2466203           0.633313            0.08224513        
alternative "two.sided"         "two.sided"         "two.sided"      
method      "One Sample t-test" "One Sample t-test" "One Sample t-test"
data.name   "X[[i]]"            "X[[i]]"            "X[[i]]"

例2

> y1<-rpois(20,5)
> y2<-rpois(20,2)
> y3<-rpois(20,5)
> df2<-data.frame(y1,y2,y3)
> df2
输出结果
   y1 y2 y3
1   4  2  4
2   4  1  2
3   6  1  5
4   4  3  7
5   5  4  2
6   4  4  5
7   7  3  6
8   4  0  8
9   3  0  4
10  4  4  4
11  5  2  3
12  8  2  7
13  4  4  3
14  8  1  6
15  7  3  7
16  3  2  6
17  4  0  1
18  1  3  3
19  2  3  2
20  3  4  4

在df2的所有列上应用t检验-

> sapply(df2,t.test)
输出结果
                  y1                  y2                  y3                
statistic   10.71684            7.254174            9.888889          
parameter   19                  19                  19                
p.value     1.706058e-09        6.946248e-07        6.298981e-09      
conf.int    Numeric,2           Numeric,2           Numeric,2        
estimate    4.5                 2.3                 4.45              
null.value  0                   0                   0                
stderr      0.4198997           0.3170589           0.45              
alternative "two.sided"         "two.sided"         "two.sided"      
method      "One Sample t-test" "One Sample t-test" "One Sample t-test"
data.name   "X[[i]]"            "X[[i]]"            "X[[i]]"