rbrms

How to pass variables into brms model


I often save my priors for mean and sd as variables (e.g., SD_INTERCEPT), but I cannot pass these variables into my brms model. Is there a way to do this?

library(tidyverse)
library(brms)

df_demo = 
    tibble(
        A = rbinom(1e3, 1, .5),
        B = rbinom(1e3, 1, .51),
    ) |> 
    pivot_longer(
        everything(),
        names_to = "recipe",
        values_to = "convert"
    )

MU_INTERCEPT = 0
SD_INTERCEPT = 0.1003353
MU_TRT = 0
SD_TRT = 0.02000267

brm(
    formula = "convert ~ recipe",
    prior =
        prior(normal(MU_INTERCEPT, SD_INTERCEPT), class = Intercept) +
        prior(normal(MU_TRT, SD_TRT), class = b, coef=recipeB),
    data = df_demo, 
    family = bernoulli
    ) 
Error in stanc(file = file, model_code = model_code, model_name = model_name,  : 
  0
Semantic error in 'string', line 27, column 36 to column 48:
   -------------------------------------------------
    25:    real lprior = 0;  // prior contributions to the log posterior
    26:    lprior += normal_lpdf(b[1] | 0, 0.02000267);
    27:    lprior += normal_lpdf(Intercept | MU_INTERCEPT, SD_INTERCEPT);
                                             ^
    28:  }
    29:  model {
   -------------------------------------------------

Identifier 'MU_INTERCEPT' not in scope.

Solution

  • The prior argument of the parent function brms::set_prior() is defined as "A character string defining a distribution in Stan language". Among the helpers there are the following:

    So while prior() allows you to do away with quotes it still forwards the raw call as a string, and Stan has no idea what those literal constants are.

    You can use the prior_string() helper or the main set_prior() to evaluate arguments on the R side -- making sure all of them are now provided as quoted characters:

      prior =
        prior_string(paste0("normal(", MU_INTERCEPT, ", ", SD_INTERCEPT, ")"), class = "Intercept") +
        prior_string(paste0("normal(", MU_TRT, ", ", SD_TRT, ")"), class = "b", coef="recipeB")