## Not run:
# ### Usage with stanfit objects
# log_lik1 <- extract_log_lik(stanfit1) # see ?extract_log_lik
# loo1 <- loo(log_lik1)
# print(loo1, digits = 3)
#
# log_lik2 <- extract_log_lik(stanfit2)
# (loo2 <- loo(log_lik2))
# compare(loo1, loo2)
# ## End(Not run)
### Using log-likelihood function instead of matrix
set.seed(024)
# Simulate data and draw from posterior
N <- 50; K <- 10; S <- 100; a0 <- 3; b0 <- 2
p <- rbeta(1, a0, b0)
y <- rbinom(N, size = K, prob = p)
a <- a0 + sum(y); b <- b0 + N * K - sum(y)
draws <- rbeta(S, a, b)
data <- data.frame(y,K)
llfun <- function(i, data, draws) {
dbinom(data$y, size = data$K, prob = draws, log = TRUE)
}
loo_with_fn <- loo(llfun, args = nlist(data, draws, N, S), cores = 1)
# Check that we get same answer if using log-likelihood matrix
log_lik_mat <- sapply(1:N, function(i) llfun(i, data[i,, drop=FALSE], draws))
loo_with_mat <- loo(log_lik_mat, cores = 1)
all.equal(loo_with_mat, loo_with_fn)
Run the code above in your browser using DataLab