knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "tools/README-" )
tmbr
(pronounced timber) is an R package to facilitate analyses using Template Model Builder (TMB
).
It is part of the mbr family of packages.
library(magrittr) library(ggplot2) library(mbr) library(tmbr)
model <- model("#include <TMB.hpp> template<class Type> Type objective_function<Type>::operator() () { DATA_VECTOR(Pairs); DATA_VECTOR(Year); DATA_FACTOR(Annual); DATA_INTEGER(nAnnual); PARAMETER(alpha); PARAMETER(beta1); PARAMETER(beta2); PARAMETER(beta3); PARAMETER_VECTOR(bAnnual); PARAMETER(log_sAnnual); Type sAnnual = exp(log_sAnnual); vector<Type> ePairs = Pairs; Type nll = 0.0; for(int i = 0; i < nAnnual; i++){ nll -= dnorm(bAnnual(i), Type(0), sAnnual, true); } for(int i = 0; i < Pairs.size(); i++){ ePairs(i) = exp(alpha + beta1 * Year(i) + beta2 * pow(Year(i), 2) + beta3 * pow(Year(i), 3) + bAnnual(Annual(i))); nll -= dpois(Pairs(i), ePairs(i), true); } ADREPORT(sAnnual) return nll; }") # add R code to calculate derived parameters model %<>% update_model(new_expr = " for (i in 1:length(Pairs)) { log(prediction[i]) <- alpha + beta1 * Year[i] + beta2 * Year[i]^2 + beta3 * Year[i]^3 + bAnnual[Annual[i]] }") # define data types and center year model %<>% update_model( gen_inits = function(data) list(alpha = 4, beta1 = 1, beta2 = 0, beta3 = 0, log_sAnnual = 0, bAnnual = rep(0, data$nAnnual)), select_data = list("Pairs" = integer(), "Year*" = integer(), Annual = factor()), random_effects = list(bAnnual = "Annual")) data <- bauw::peregrine data$Annual <- factor(data$Year) analysis <- analyse(model, data = data) coef(analysis)
year <- predict(analysis, new_data = "Year") ggplot(data = year, aes(x = Year, y = estimate)) + geom_point(data = bauw::peregrine, aes(y = Pairs)) + geom_line() + expand_limits(y = 0)
To install from GitHub
install.packages("devtools") devtools::install_github("poissonconsulting/tmbr")
citation(package = 'tmbr')
Please report any issues.
Pull requests are always welcome.
Please note that the tmbr project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.