在 R 中创建具有 t 统计量的矩阵

Creating a matrix with t-statistics in R

我有一个面板数据集,想创建一个类似于相关矩阵的矩阵,但仅具有 t 检验估计值和 t 统计量的差异。

使用牙齿生长数据,我首先根据剂量值对 supp id 进行分组,我想计算子组之间所有可能组合的 t 统计量。

我希望我的 t 检验矩阵如下所示

          VC_all  VC_0.5     VC_1  VC_all    VC_0.5  VC_1  OJ_all  OJ_0.5  OJ_1                                                             

VC_all                                                  -4 ( -1.92 )       
VC_0.5
VC_1
VC_all
VC_0.5
VC_1
OJ_all
OJ_0.5
OJ_1

作为例子,我用下面的公式填充了一个值

t_test <- t.test(x = filter(ToothGrowth, supp== "VC")$len,
                 y = filter(ToothGrowth, supp== "OJ")$len, var.equal = TRUE)

有没有更快的方法来计算每个分组的所有 t-stats?

df["VC_all","OJ_all"] <- paste(round(t_test$estimate[1] - t_test$estimate[2]), 
                               "(", round(t_test$statistic,2), ")")

你可以用这个

# generate data
df <- data.frame(matrix(rnorm(100*3), ncol= 3))
# name data
names(df) <- c("a", "b", "c")

# or to use for your data
df <- name_of_your_dataframe

# make a dataframe for the results
results <- data.frame(matrix(rep(NA, ncol(df)*ncol(df)), ncol= ncol(df)))
# name the results dataframe
names(results) <- names(df)
rownames(results) <- names(df)
# between which columns do we need to run t-tests?
to_estimate <- t(combn(names(df), 2))
# replace upper triangle of the matrix with the results
results[upper.tri(results)] <- apply(to_estimate, 1, function(to_estimate_i){
t_results <- t.test(df[ , to_estimate_i[1]], df[ , to_estimate_i[2]])
out <-  paste0(round(t_results$estimate[1] - t_results$estimate[2], 2), " (", round(t_results$statistic, 2), ")")
})
# copy upper to lower
results[lower.tri(results)] <- results[upper.tri(results)]

您需要做的就是将 df 替换为数据框的名称