# NOT RUN {
## NOTE: The values below MUST NOT be used in a real application;
## they are only used here to make the examples run quick!!!
example_mcmc_control <- list(n.burnin = 10, n.iteration = 100,
n.thin = 1)
library(mvabund) ## Load a dataset from the mvabund package
data(spider)
y <- spider$abun
n <- nrow(y)
p <- ncol(y)
## Example 1 - model with two latent variables, site effects,
## and no environmental covariates
spiderfit_nb <- boral(y, family = "negative.binomial",
lv.control = list(num.lv = 2), row.eff = "fixed", save.model = TRUE,
mcmc.control = example_mcmc_control)
## Extract all MCMC samples
fit_mcmc <- get.mcmcsamples(spiderfit_nb)
mcmc_names <- colnames(fit_mcmc)
## Find the posterior medians
coef_mat <- matrix(apply(fit_mcmc[,grep("lv.coefs",mcmc_names)],
2,median),nrow=p)
site_coef <- list(ID1 = apply(fit_mcmc[,grep("row.coefs.ID1", mcmc_names)],
2,median))
## Calculate the marginal log-likelihood at the posterior median
calc.marglogLik(y, family = "negative.binomial",
lv.coefs = coef_mat, row.eff = "fixed", row.params = site_coef,
num.lv = 2)
## Example 2 - model with one latent variable, no site effects,
## and environmental covariates
spiderfit_nb2 <- boral(y, X = spider$x, family = "negative.binomial",
lv.control = list(num.lv = 2), save.model = TRUE,
mcmc.control = example_mcmc_control)
## Extract all MCMC samples
fit_mcmc <- get.mcmcsamples(spiderfit_nb2)
mcmc_names <- colnames(fit_mcmc)
## Find the posterior medians
coef_mat <- matrix(apply(fit_mcmc[,grep("lv.coefs",mcmc_names)],
2,median),nrow=p)
X_coef_mat <- matrix(apply(fit_mcmc[,grep("X.coefs",mcmc_names)],
2,median),nrow=p)
## Calculate the log-likelihood at the posterior median
calc.marglogLik(y, X = spider$x, family = "negative.binomial",
lv.coefs = coef_mat, X.coefs = X_coef_mat, num.lv = 2)
# }
Run the code above in your browser using DataLab