library(tweedie)
# Simulação de
dados
period<-factor(1:4)
herd<-factor(1:10)
dat<-expand.grid(period=period,herd=herd)
beta<-c(-.3,1.7,2.5,3.4)
x<-model.matrix(~period,dat)
b<-rnorm(length(levels(dat$herd)),sd=.3)
z<-model.matrix(~-1+herd,dat)
mu<-as.vector(exp(x%*%beta+z%*%b))
phi<-.8; p<-1.6
dat$resp<-rtweedie(nrow(dat),p,mu,phi)
y<-dat$resp
th<-c(rep(0,ncol(x)),1,1,1.5)
beta<-th[1:ncol(x)]
sig<-th[ncol(x)+1]
phi<-th[ncol(x)+2]
p<-th[ncol(x)+3]
z.ast<-sig*z
l.u<-function(u,y,z,x,beta,phi,p){
eta.u<-as.vector(x%*%beta+z%*%u)
f.y<-log(dtweedie(y,p,exp(eta.u),phi))
l.yu<-sum(f.y)+sum(dnorm(u,log=T))
return(-l.yu)
}
uhat<-optim(rep(0,ncol(z)),l.u,method="BFGS",hessian=T,
y=y,z=z.ast,x=x,beta=beta,phi=phi,p=p)