多元向量回归和系数提取
Regression with multivariate vectors and coefficients extraction
我想创建 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 个回归然后提取系数,我将不胜感激。
我们可以编写自定义回归函数。
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 个估计值。
我想创建 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 个回归然后提取系数,我将不胜感激。
我们可以编写自定义回归函数。
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 个估计值。