1
votes

I want to create 1000 samples of 200 bivariate normally distributed vectors

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)

so that I can run OLS regressions on each sample and therefore get 1000 estimators. I tried this

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

but I am stuck there, because now I don't know how to proceed to run the regression for each sample.

I would appreciate the help to know how to run these 1000 regressions and then extract the coefficients.

1
I just tried that, but I got descriptive statistics and a row of NAs :(Alex Ruiz
Try sapply(bivn_1000, function(x) summary(lm(x[, 1] ~ x[, 2]))$coef). Your data is bivariate though, or am I wrong?jay.sf
Yes. Each sample contains 200 bivariate vectors, and I am trying to create 1000 samplesAlex Ruiz
Please see my answer below.jay.sf

1 Answers

0
votes

We could write a custom regression function.

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

which we can loop over the data with lapply:

l1 <- lapply(bivn_1000, regFun1)

The coefficients are saved inside a list and can be extracted like so:

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

Edit:

If we solely want the estimators without statistics, we adjust the output of the function accordingly.

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

Since we may want the output in matrix form we use sapply next.

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

where

dim(m2)
# [1] 1000    2

assures us that we have our 1,000 estimates.