# Code Snippets Stan

Short texts Stan 🧑‍💻 Code snippets Stan ✍️ Reading lists Stan 👀

## Poisson-binomial multinomial distance sampling model in Stan, with half-normal detection function

data { int n_site; int n_distance_bins; vector[n_distance_bins + 1] bin_breakpoints; array[n_site, n_distance_bins] int y; array[n_site] int n_obs; } transformed data { real max_distance = max(bin_breakpoints); real log_two = log(2); real log_max_distance_sq = 2 * log(max(bin_breakpoints)); vector[n_distance_bins + 1] bin_breakpoints_sq = bin_breakpoints^2; } parameters { real log_lambda; real log_sigma; } transformed parameters { real log_p; vector[n_distance_bins] […]

## stan_lkj_corr.stan

data{ int N; // number of observations corr_matrix y[N]; // A n-element arrary of observed correlation matrix [N, 2, 2] } parameters{ real eta; } model{ for(i in 1:N){ y[i, ,] ~ lkj_corr(eta); // y[i,] and y[i, ,] should also be fine } }

## Multinomial regression model

/* This model is based on the multinomial model in Bayesian Data Analysis 3, p426. I used the multinomial regression example from the Stan website https://mc-stan.org/docs/2_27/stan-users-guide/multi-logit-section.html and then modified it to match our model. For this model to work, you need an up to date version of `rstan`, at least 2.26.2. Follow the instructions here: […]

## Stan vs LME4 for hiearchical within-subjects designs with binomial outcomes

#’ Installs any packages not already installed #’ @examples #’ \dontrun{ #’ install_if_missing(c(‘tidyverse’,’github.com/stan-dev/cmdstanr’)) #’ } install_if_missing = function(pkgs){ missing_pkgs = NULL for(this_pkg in pkgs){ path = NULL try( path 0){ message(‘The following required but uninstalled CRAN packages will now be installed:\n’,paste(cran_missing,collapse=’\n’)) install.packages(cran_missing) } github_missing = missing_pkgs[grepl(‘github.com/’,fixed=T,missing_pkgs)] github_missing = gsub(‘github.com/’,”,github_missing) if(length(github_missing)>0){ message(‘The following required but uninstalled […]