多元向量回归与系数提取

时间:2019-04-19 05:14:24

标签: r regression multivariate-testing

我想创建200个二元正态分布矢量的1000个样本

set.seed(42)  # for sake of reproducibility
mu <- c(1, 1)
S <- matrix(c(0.56, 0.4,
              0.4, 1), nrow=2, ncol=2, byrow=TRUE)
bivn <- mvrnorm(200, mu=mu, Sigma=S)

这样我就可以对每个样本进行OLS回归,从而获得1000个估计量。我尝试过了

library(MASS)
bivn_1000 <- replicate(1000, mvrnorm(200, mu=mu, Sigma=S), simplify=FALSE)

但是我被困在那里,因为现在我不知道如何继续对每个样本进行回归。

我很高兴能帮助您了解如何运行这1000个回归,然后提取系数。

1 个答案:

答案 0 :(得分:0)

我们可以编写一个自定义回归函数。

regFun1 <- function(x) summary(lm(x[, 1] ~ x[, 2]))

我们可以使用lapply遍历数据:

l1 <- lapply(bivn_1000, regFun1)

系数保存在列表中,可以像这样提取:

l1[[1]]$coefficients  # for the first regression
#              Estimate Std. Error   t value     Pr(>|t|)
# (Intercept) 0.5554601 0.06082924  9.131466 7.969277e-17
# x[, 2]      0.4797568 0.04255711 11.273246 4.322184e-23

编辑:

如果我们只希望估算器没有统计信息,那么我们将相应地调整函数的输出。

regFun2 <- function(x) summary(lm(x[, 1] ~ x[, 2]))$coef[, 1]

由于我们可能希望以矩阵形式输出,因此接下来使用sapply

m2 <- t(sapply(bivn_1000, regFun2))

head(m2)
#      (Intercept)    x[, 2]
# [1,]   0.6315558 0.4389721
# [2,]   0.5514555 0.4840933
# [3,]   0.6782464 0.3250800
# [4,]   0.6350999 0.3848747
# [5,]   0.5899311 0.3645237
# [6,]   0.6263678 0.3825725

其中

dim(m2)
# [1] 1000    2

向我们保证我们有1,000个估算值。