I have a simple poisson model with unobserved heterogeneity eta that is normally distributed. This can be solved by integrating eta out of the log-likelihood. However when i try to do this it produces wrong coefficients and i can't see why. The code is shown below. It should return coefficients for beta and sigma close to 0.018 and 0.013 correspondingly, but it does not.
library("maxLik")
library("pracma")
library("rmutil")
n = 3000
x = rnorm(n, mean=0, sd=2)
beta1 = 0.018
sigma = 0.013
eta = rnorm(n, mean=0, sd= sigma)
mu = exp(x*beta1 + eta)
y = rpois(n,mu)
poisson <- function(y,mu) {
a = mu^y*exp(-mu)/factorial(y)
return(a)
}
loglik <- function(param) {
beta = param[1]
sigma = param[2]
f <- function(eta) dnorm(eta, sd = sigma)*poisson(y, exp((x*beta + eta)))
ll <- int(f, a = -100, b = 100)
ll[ll==0] <- 0.00000000001
logll = log(ll)
return((sum(logll)))
}
bet = runif(16, min=-1, max = 0)/10
ml <- maxLik(loglik, start = c(beta= 0.1, sigma = 0.1), print.level = 2)