簡體   English   中英

通過引導R中的數據來復制函數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM