Skip to content

Extract groups from intercept names with spread/gather_draws #321

@JackCaster

Description

@JackCaster

I would like to extract draws from a model that has an intercept that varies with a predictor with spread/gather_draws.

When the model is specified as y ~ 0 + group it results in a brms model with variables "b_groupA" and "b_groupB". But it is not possible to extract the group using m %>% gather_draws(b_group[group]). What it is possible is to extract the intercepts using regex but not the group index variable:

m  %>%
    gather_draws(`b_.*`, regex = TRUE)
# Groups:   .variable [2]
   .chain .iteration .draw .variable .value
    <int>      <int> <int> <chr>      <dbl>
 1      1          1     1 b_groupA    104.
 2      1          2     2 b_groupA    104.
 3      1          3     3 b_groupA    104.
 4      1          4     4 b_groupA    104.
 5      1          5     5 b_groupA    106.
 6      1          6     6 b_groupA    105.

So far, the workaround for me has been to use separate_wider_regex but things get complex quite quickly.

Do you think your functions can be adapted to cover such scenario?

Code:

library(tidyverse)
library(brms)
library(tidybayes)

N <- list(a = 25, b = 30) # sample size
MEAN <- list(a = 105, b = 103) # population mean
SD <- list(a = 2, b = 5) # population sd

ya <- tibble(y = rnorm(N$a, mean = MEAN$a, sd = SD$a))
yb <- tibble(y = rnorm(N$b, mean = MEAN$b, sd = SD$b))

df <- bind_rows(list(A = ya, B = yb), .id = "group")

m  <- brm(y ~ 0 + group, data = df)

get_variables(m)
#  [1] "b_groupA"      "b_groupB"      "sigma"         "lprior"        "lp__"          "accept_stat__" "treedepth__"   "stepsize__"    "divergent__"   "n_leapfrog__"  "energy__"     

m  %>%
    gather_draws(`b_.*`, regex = TRUE)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions