knitr::opts_chunk$set(echo = TRUE)
library(MASS)
library(brms)
library(ggplot2)

Generate simple data

Let’s assume that our data $y$ is real valued and our predictor is “Age”.

y <- rnorm(30, mean = 1, sd = 2)
dat1 <- data.frame(y)
dat1$age <- rnorm(30, mean = 40, sd = 10)
head(dat1)

Understanding the priors

Let’s imagine we want to create a simple model of the form \(y \sim N(\mu, \sigma)\) where \(\mu = a + b \cdot Age\).

model_formula<- bf(y ~ 1 + age)

To understand the model we need to use get_prior and make_stancode. We need to explore the output of the two to learn how to set custom priors.

get_prior(model_formula,data = dat1, family = gaussian())

The best way to enter priors is to save the output dataframe of get_priors and edit it directly. Let’s first explore the resulting Stan code to understand where the priors will be set

make_stancode(model_formula,data = dat1, family = gaussian())

We see that parameters are b; // population-level effects , real temp_Intercept; // temporary intercept, and real<lower=0> sigma // residual SD. Let’s match that to the dataframe of priors

priors <- get_prior(model_formula,
            data = dat1, family = gaussian())
priors

Let’s give normal priors to the

priors$prior[2] <- "normal(0,10)"
priors$prior[3] <- "normal(0,1000)"
priors$prior[4] <- "cauchy(0,10)"

priors

And check that the generated Stan code reflects the change

make_stancode(bf(y ~  age),data = dat1, family = gaussian(), prior = priors)

Note that if we had made a typo or passed a distribution that is not part of Stan we would get an error. The following code is not evaluated, if it was it would raise an error.

priors$prior[4] <- "clichy(0,10)"
make_stancode(bf(y ~  age),data = dat1, family = gaussian(), prior = priors)

References