library(mvabund) ## Load a dataset from the mvabund package
data(spider)
y <- spider$abun
n <- nrow(y); p <- ncol(y);
## Example 1 - model with 2 latent variables, site effects,
## and no environmental covariates
spider.fit.nb <- boral(y, family = "negative.binomial", num.lv = 2,
site.eff = TRUE, save.model = TRUE, calc.ics = FALSE)
## Extract all MCMC samples
fit.mcmc <- as.mcmc(spider.fit.nb$jags.model)[[1]]
## Find the posterior medians
coef.mat <- matrix(apply(fit.mcmc[,grep("all.params",colnames(fit.mcmc))],
2,median),nrow=p)
site.coef.median <- apply(fit.mcmc[,grep("site.params", colnames(fit.mcmc))],
2,median)
lvs.mat <- matrix(apply(fit.mcmc[,grep("lvs",colnames(fit.mcmc))],2,median),nrow=n)
## Caculate the conditional log-likelihood at the posterior median
calc.condlogLik(y, family = "negative.binomial",
lv.coefs = coef.mat, site.coefs = site.coef.median, lv = lvs.mat)
## Example 2 - model with one latent variable, no site effects,
## and environmental covariates
spider.fit.nb2 <- boral(y, X = spider$x, family = "negative.binomial", num.lv = 1,
site.eff = FALSE, save.model = TRUE, calc.ics = FALSE)
## Extract all MCMC samples
fit.mcmc <- as.mcmc(spider.fit.nb2$jags.model)[[1]]
## Find the posterior medians
coef.mat <- matrix(apply(fit.mcmc[,grep("all.params",colnames(fit.mcmc))],
2,median),nrow=p)
X.coef.mat <- matrix(apply(fit.mcmc[,grep("X.params",colnames(fit.mcmc))],
2,median),nrow=p)
lvs.mat <- matrix(apply(fit.mcmc[,grep("lvs",colnames(fit.mcmc))],2,median),nrow=n)
## Caculate the log-likelihood at the posterior median
calc.condlogLik(y, X = spider$x, family = "negative.binomial",
lv.coefs = coef.mat, X.coefs = X.coef.mat, lv = lvs.mat)
Run the code above in your browser using DataLab