我正在尝试使用 OLS(矩阵形式)估计 = (, )′ 并将值存储在维度 × 2 的矩阵中,并进行 monte carlo 模拟

I am trying to estimate = (, )′ using OLS(matrix form) and store the values in a matrix of dimension × 2, with monte carlo simulation

我不太明白如何将值存储在维度 × 2 的矩阵中。这就是我在 R 中的进展:

我的回归:=0+1+,其中 B0=1 且 B1=-1

set.seed(123)
n = 20
nreps=10000
beta_0 = -1 
beta_1 = 1 

ols = vector(mode="numeric", length=nreps)

##Start MC

for (r in 1:nreps) {
  u = rnorm(n, mean = 0, sd = 1) 
  x = rnorm(n, mean = 1, sd = 2^2) 
  y = beta_0 + beta_1*x + u
  
  head(x)

  beta_hat=solve(t(x) %*% x) %*% (t(x) %*% y)
  beta_hat 
  
  # print(paste("OLS estimate =", beta_hat))4f
  
  ols[r] = beta_hat
}
ols = cbind(ols)
ols_average=mean(ols[,1])
ols_sd=sd(ols[,1])
plot(density(ols)) 

要估计模型的系数,请使用 lsfitlm 使用的低级函数。

set.seed(307)
n <- 20
nreps <- 10000
beta_0 <- -1 
beta_1 <- 1 

beta_mat <- matrix(nrow = nreps, ncol = 2,
                   dimnames = list(NULL, c("Intercept", "x")))
for (r in seq.int(nreps)) {
  u <- rnorm(n, mean = 0, sd = 1) 
  x <- rnorm(n, mean = 1, sd = 2^2) 
  y <- beta_0 + beta_1*x + u
  fit <- lsfit(x, y)
  beta_mat[r, ] <- coef(fit)
}

beta_average <- colMeans(beta_mat)
beta_average
#Intercept         x 
#-1.005184  1.001375 


beta_sd <- apply(beta_mat, 2, sd)

dens <- density(beta_mat[,2])

hist(beta_mat[,2], freq = FALSE, ylim = c(0, 1.1*max(dens$y)),
     xlab = expression(beta[1]), main = expression("Histogram of" ~ beta[1]))
lines(dens)