Thanks in advance!
Tomas
library(RTMB)
N <- 9000
d <- data.frame(present = rbinom(N, 1, 0.3))
inv.logit <- plogis
# log likelihood but I need the vector for each data point rather than just a sum
ll_pa <- function (data, par)
{
y <- data
p <- inv.logit(par)
y0 <- y$present == 0
y1 <- y$present == 1
ll_ <- numeric(nrow(y))
ll_[y1] <- log(p[y1])
ll_[y0] <- log(1 - p[y0])
sum(ll_)
}
cmb <- function(f, data) function(par) f(data, par)
# closure trick somewhere from the RTMB docs, to tie this to particular data and prevent unnecessary headaches!
F <- MakeTape(cmb(ll_pa, data = d), numeric(N))
p1 <- rnorm(N)
F$jacobian(p1) # first derivatives are alright
# second derivatives
der2 <- F$jacfun()$jacobian(p1)
# takes too long, calculating the whole hessian matrix, when I need just the diagonal
der2b <- F$jacfun(sparse = TRUE)$jacobian(p1) # surprisingly, this yields exactly the same result
identical(der2, der2b)