rbrmshierarchical-bayesian

posterior draws without including hyperparameters from hierarchical model


I have a hierarchical Bayesian model that I fit with brms. Is it possible to draw samples from the posterior where I don't specify a specific grouping from the hierarchical term? Essentially, I'm trying to look at what the distribution would be for the general relationship.

Example dataset and model:
df <- data.frame(site  = sample(LETTERS[1:5], 200, replace = TRUE),
                 water = runif(200, 0, 1),
                 year  = factor(sample(c(1:3), 200, replace = TRUE)),
                 mass  = rnorm(200, 20, 3))
m <- brm(mass ~ water + (1 | year) + (1 | site), data = df)

# both methods I know of for obtaining values from the posterior come with the model hyperparameters
add_predicted_draws(df, m)
as_draws_df(m)

Alternatively, what data goes into the conditional_effects() plots? And how could I extract that raw data?

conditional_effects(m)

Solution

  • This was my solution to this question (example given for the first. It's likely not perfect and I'm open to other suggestions too.

    as_draws_df(m) %>%                       
      select(b_Intercept, b_water) %>% 
      reframe(water = seq(min(df$water), max(df$water), 0.1), 
              .by = c("b_Intercept", "b_water")) %>% 
      mutate(predMass = exp(b_Intercept + b_water * water)) %>% 
      group_by(water) %>% 
      summarise(meanPredMass = mean(predMass),
                loPredMass   = quantile(predMass, prob = 0.025),
                hiPredMass   = quantile(predMass, prob = 0.975)) %>%
      ggplot(aes(x = water)) +
      geom_ribbon(aes(ymin = loPredMass, ymax = hiPredMass), fill = "grey80") +
      geom_line(aes(y = meanPredMass)) +
      labs(y = "conditional mean mass (95% CI)", x = "water")
    

    enter image description here