Reputation: 516
I am estimating a GMM model using library(gmm)
.
n <- 200
x1 <- rnorm(n)
x2 <- rnorm(n)
x3 <- rnorm(n)
x4 <- rnorm(n)
x5 <- rnorm(n)
x6 <- rnorm(n)
xx <- cbind(x1, x2, x3, x4, x5, x6)
fun <- function(betastar, x) {
m1 <- (x[,1] - x[,2]*betastar - x[,3] - x[,4])*x[,5]
m2 <- (x[,1] - x[,2]*betastar - x[,3] - x[,4])*x[,6]
f <- cbind(m1,m2)
return(f)
}
library(gmm)
k <- gmm(fun, x=xx, 0, optfct="optim", lower = 0, upper = 2, method="Brent")
I want to replicate it B
times by bootstrapping my sample xx
(with replacement). My scope is to save the standard errors of betastar for each replication and store all of them somewhere. Is there a fast way to do that ?
I know there is the library(boot)
which in principle should allow me to do that, but I am having an hard time to figure out how, since for using the function gmm I need to specify another function (fun
)
EDIT: What the gmm
function is doing is minimizing the other function fun
with respect to the parameter betastar
. All the terms in gmm()
define the way gmm
works. What I want is to bind betastar (which is a coefficient) and its standard error in an object, for any 1:B replication. They can be recovered by the commands coef(k)
and sqrt(k$vcov)
I am trying the following
B <- 199 # number of bootstrapping
betak_boot <- rep(NA, 199)
se_betak_boot <- rep(NA, 199)
for (ii in 1:B){
sample <- (replicate(ii, apply(xx, 2, sample, replace = TRUE)))
k_cons <- gmm(fun, x=samples, 0, gradv=Dg, optfct="optim", lower = 0, upper = 2, method="Brent")
betak_boot[ii] <- coef(k_cons)
se_betak_boot[ii] <- sqrt(k_cons$vcov)
}
I don't know why, I get an error while applying fun
, i.e. Error in x[, 1] : incorrect number of dimensions
. Indeed, I don't know why sample
is
dim(sample)
[1] 200 6 1
Upvotes: 3
Views: 356
Reputation: 543
library(gmm)
set.seed(123)
n <- 200
x1 <- rnorm(n)
x2 <- rnorm(n)
x3 <- rnorm(n)
x4 <- rnorm(n)
x5 <- rnorm(n)
x6 <- rnorm(n)
xx <- cbind(x1, x2, x3, x4, x5, x6)
fun <- function(betastar, x) {
m1 <- (x[,1] - x[,2]*betastar - x[,3] - x[,4])*x[,5]
m2 <- (x[,1] - x[,2]*betastar - x[,3] - x[,4])*x[,6]
f <- cbind(m1,m2)
return(f)
}
ii=4
samples <- replicate(ii, apply(xx, 2, sample, replace = TRUE))
coefk <- rep(0,ii)
sdk <- rep(0,ii)
for (i in 1:ii) {
xx <- samples[,,i]
k <- gmm(fun, x=xx, 0, optfct="optim", lower = 0, upper = 2, method="Brent")
coefk[i] <- coef(k)
sdk[i] <- sqrt(k$vcov)[1,1]
}
Upvotes: 1