簡體   English   中英

R:使用gmm包進行索引

[英]R: Index out of bound using gmm package

我是Stackoverflow的新手,這篇文章可能非常基礎。 我使用“gmm”包得到了意外的“索引列表外”錯誤。 更具體地說,我正在使用該包的凝膠功能,我需要提供參數“g”,這是一個返回矩陣的函數。 我傳遞給“g”參數的函數本身完全有效,但不作為凝膠函數的參數。 我知道有一個非常密切相關的問題: https//stackoverflow.com/search?q= index+out+of+ bounds+r然而,這些都沒有幫助我解決我面臨的問題。 我附上了一個可重復的例子。

提前致謝。

rm(list=ls())
install.packages("gmm")
library(mvtnorm)
library(gmm)
#set.seed(1)


########################################
#functions declaration and construction#
########################################

moment.function <- function(data,alpha) {

    instrus.index <- length(alpha)+1
    data<-as.matrix(data)
    nbr.instrus <- ncol(data)-instrus.index
    data1 <-data[,1]-data[,(2:instrus.index)]%*%alpha
    data1<-matrix(rep(data1,nbr.instrus),nrow(total.data),nbr.instrus)
    g.fun <- data[,-(1:instrus.index)]*data1
    #g.fun <- t(data[,-(1:instrus.index)])%*%(data[,1]-data[,(2:instrus.index)]%*%alpha)
    return(g.fun)
}


##################
#DGP construction#
##################

#set params
n <- 70
beta1 <- 1
beta2 <- 1
beta.first.stage <- 0.1
rho <- 0.1
cov.exo.instrus <- 0.3
sigma2.epsilon <- 0.1
sigma2.V <- 0.1
sigma2.simus <-0.01
Sigma <- rbind(c(1,cov.exo.instrus,cov.exo.instrus),
    c(cov.exo.instrus,1,cov.exo.instrus),
    c(cov.exo.instrus,cov.exo.instrus,1))


#generate obs according to DGP

#instruments and exogenous covariates
X <- rmvnorm(n, rep(0,3), Sigma)

#two disturbance terms
epsilon<-rnorm(n,0,sigma2.epsilon)
V <- rnorm(n,0,sigma2.V)

#endogenous regressor
Y2 <- beta.first.stage*(X[,2]+X[,3])+V


#outcome variable with structural error term
#h()=()^2
Y1 <- beta1*X[,1]+beta2*(Y2^2+sigma2.V-V^2-2*beta.first.stage*(X[,2]+X[,3])*V)+epsilon


#matrices for the finite-dimensional case
second.stage.vars <- cbind(Y1,X[,1],Y2^2)
total.data <- cbind(second.stage.vars,X)

###################################


#simulations in the finite-dimensional case

#with gel there is a problem
gel(moment.function, total.data, c(1.5, 1.5))

#moment.function alone has no problem
moment.function(total.data,c(1.5,1.5))

gmm函數期望數據的參數和參數是相反的,即你的矩函數應該是

moment.function <- function(alpha, data) {
  ## function body
}

有了這個改變,你的例子對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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