使用 R 中的排列值从模型中获取汇总统计信息

Getting summary statistics from model using permutation values in R

我正在尝试获取线性模型(下方)的汇总统计数据(summary()),它使用原始数据集的 1000 个排列来创建 1000 个随机数据集(大矩阵)。

random_model <- rep(NA,1000)

for (i in c(1:1000)) {
  random_data <- final_data
  random_data$weighted_degree <- rowSums(node.perm_1000[i,,],na.rm=T)
  random_model[i] <- coef(lm(weighted_degree ~ age + sex + age*sex, data=random_data))
}

我不是简单地尝试比较模型以获得总体 p 值,而是我还想为使用随机排列的模型中的每个变量获取 t 值。

尝试使用 broom 包中的 tidy()。它 returns 这样的预期值(示例):

# A tibble: 2 x 5
  term             estimate std.error statistic  p.value
  <chr>               <dbl>     <dbl>     <dbl>    <dbl>
1 (Intercept)         6.53      0.479     13.6  6.47e-28
2 iris$Sepal.Width   -0.223     0.155     -1.44 1.52e- 1

在您的情况下,将根据您的定义为循环列表中的每个元素存储先前的输出:

library(broom)
#Data
random_model <- rep(NA,1000)
#Loop
for (i in c(1:1000)) {
  random_data <- final_data
  random_data$weighted_degree <- rowSums(node.perm_1000[i,,],na.rm=T)
  random_model[i] <- broom::tidy(lm(weighted_degree ~ age + sex + age*sex, data=random_data))
}

您应该将感兴趣的结果(估计系数和 t-values)存储在列表中。

这是一个在 mtcars 数据集上使用 10 次复制的可重现示例,每次复制都以 50% 的速率进行采样。

使用 lm 对象上 summary() 输出的 $coefficients 属性检索感兴趣的结果。

# The data
data(mtcars)

# Define sample size of each replication
N <- nrow(mtcars)
sample_size <- floor(N/2)

# Number of replications (model fits) and initialization of the list to store the results 
set.seed(1717)
replications <- 10
random_model <- vector( "list", length=replications )
for (i in seq_along(random_model)) {
  shuffle = sample(N, sample_size)
  mtcars_shuffle = mtcars[shuffle, ]
  random_model[[i]] <- summary(lm(mpg ~ cyl + disp + cyl*disp, data=mtcars_shuffle))$coefficients
}

例如,适合复制 1 和 10 的模型是:

> random_model[[1]]
               Estimate  Std. Error   t value     Pr(>|t|)
(Intercept) 48.26285335 8.219065181  5.872061 7.573836e-05
cyl         -3.33999161 1.366231326 -2.444675 3.089262e-02
disp        -0.12941685 0.063269362 -2.045490 6.337414e-02
cyl:disp     0.01394436 0.007877833  1.770076 1.020931e-01

> random_model[[10]]
               Estimate  Std. Error   t value     Pr(>|t|)
(Intercept) 54.27312267 7.662593317  7.082866 1.277746e-05
cyl         -4.40545653 1.586392001 -2.777029 1.674235e-02
disp        -0.15330770 0.047932153 -3.198431 7.654790e-03
cyl:disp     0.01792561 0.006707396  2.672514 2.031615e-02