R:多个分组的独立 t 检验

R: Independent t-tests for multiple by groups

我有一个名为 'dat' 的数据集,其中包含 5 列:月;均值0; sd0;均值1; sd1。它看起来像以下内容(但带有数字):

月平均值0 sd0 平均值1 sd1

1
2
3
..
48

我想使用独立(非配对)t 检验来比较 1 到 48 之间每个月的 mean0 和 mean1。理想情况下,输出将放在另一个数据框中,称为 'dat1',列为:t-statisitc,自由度 (DF);和一个 p 值。像这样:

月 t 统计 DF p 值
1
2
3
..
48

我试过使用 dplyr 和 broom 包,但似乎无法弄明白。任何帮助,将不胜感激。

您还需要两个 sd 的 n 个值。 BSDA 包中的 tsum.test 函数将帮助您进行 t 检验,而无需编写自己的函数。

还有一个更大的问题,即以这种方式进行大量比较是否可取。 link 提供相关信息。

有了这个警告,下面是如何使用一些任意数据做你想做的事情:

dat <- data.frame(m1=c(24,11,34),
                  sd1=c(1.3,4.2,2.3),
                  n1=c(30, 31, 30),
                  m2=c(18,8,22), 
                  sd2=c(1.8, 3.4, 1.8),
                  n2=c(30,31,30))

# user function to do t-test and return desired values
do.tsum <- function(x) {
    # tsum.test is quirky, so you have to break out each column's value
    results <- tsum.test(x[1],x[2],x[3],x[4],x[5],x[6],alternative='two.sided')
    return(c(results$statistic, results$parameters, results$p.value))
}

# use apply to do the tsum.test on each row (1 for rows, 2 for cols)
# then, transpose the resulting matrix and use the data.frame function
t.results <- data.frame(t(apply, 1, do.tsum))s

# unfortunately the p-value is returned without no column name (it returns 'm1')
# use the names function to change the third column name.
names(t.results)[3] <- 'p.value'

输出如下:

          t       df      p.value
1 14.800910 52.78253 1.982944e-20
2  3.091083 57.50678 3.072783e-03
3 22.504396 54.83298 2.277676e-29