This is sort of a followup about RTMB and the data, but using that for predicting with new data. I'm basing my attempt partly on Kasper's suggestion above, but also on the function glmmTMB::glmmTMB.predict which I don't fully understand. I'm doing something wrong and wondered if anyone can help me figure it out. I'm using the example from the RTMB documentation, but changing it to have a data argument so that I can make predictions for my "newdata" object. The predited values I get (in black in attached graph) are completely unrealistic.
library(RTMB)
library(ggplot2)
data(ChickWeight)
parameters <- list(
mua=0, ## Mean slope
sda=1, ## Std of slopes
mub=0, ## Mean intercept
sdb=1, ## Std of intercepts
sdeps=1, ## Residual Std
a=rep(0, 50), ## Random slope by chick
b=rep(0, 50) ## Random intercept by chick
)
nll <- function(parms, data) {
getAll(data, parms, warn=FALSE)
## Optional (enables extra RTMB features)
weight <- OBS(weight)
## Initialize joint negative log likelihood
nll <- 0
## Random slopes
nll <- nll - sum(dnorm(a, mean=mua, sd=sda, log=TRUE))
## Random intercepts
nll <- nll - sum(dnorm(b, mean=mub, sd=sdb, log=TRUE))
## Data
predWeight <- a[Chick] * Time + b[Chick]
nll <- nll - sum(dnorm(weight, predWeight, sd=sdeps, log=TRUE))
## Get predicted weight uncertainties
ADREPORT(predWeight)
## Return
nll
}
cmb <- function(f, d) function(p) f(p, d)
obj <- RTMB::MakeADFun(cmb(nll, ChickWeight), parameters, random=c("a", "b"))
opt <- nlminb(obj$par, obj$fn, obj$gr)
newdata <- data.frame(Time=20:30, Diet=3, Chick=10, weight=0)
oldPar <- opt$par
H <- optimHess(oldPar,obj$fn,obj$gr)
newObj <- RTMB::MakeADFun(cmb(nll, newdata), parameters, random=c("a", "b"))
newObj$fn(oldPar) ## call once to update internal structures
sdr <- sdreport(newObj, oldPar, hessian.fixed=H, getReportCovariance=TRUE)
newdata$predWeight <- as.list(sdr, "Est", report=TRUE)$predWeight
ggplot(ChickWeight, aes(Time, weight, colour=Diet))+
geom_point()+geom_smooth()+
geom_line(data=newdata, aes(x=Time, y=predWeight), colour="black")
ggsave("extrapolate weights.png", height=3, width=5)