0

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.

1 Answer 1

1

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:

  • prior(): Alias of set_prior allowing to specify arguments as expressions without quotation marks.
  • prior_string(): Alias of set_prior allowing to specify arguments as strings.

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.