[英]Replicating a function by bootstrapping the data in R
我正在估算使用library(gmm)
的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")
我想通过引导我的样本xx
(替换)来复制它B
次。 我的范围是为每个复制保存betastar的标准错误,并将所有这些错误存储在某个地方。 有没有快速的方法来做到这一点? 我知道有一个library(boot)
,原则上应该允许我这样做,但我很难弄清楚如何,因为使用函数gmm我需要指定另一个函数( fun
)
编辑: gmm
函数正在做的是最小化关于参数betastar
的其他功能fun
。 gmm()
所有术语都定义了gmm
工作方式。 对于任何1:B复制,我想要的是绑定betastar(这是一个系数)及其在对象中的标准错误。 它们可以通过命令coef(k)
和sqrt(k$vcov)
我正在尝试以下方法
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)
}
我不知道为什么,我在应用fun
遇到错误,即Error in x[, 1] : incorrect number of dimensions
。 实际上,我不知道为什么sample
dim(sample)
[1] 200 6 1
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]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.