如何在 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

更新日期:05-11-2021

2K+ 次瀏覽

開啟你的 職業

完成課程認證

開始學習
廣告