Parameter selection in the style of dplyr and other tidyverse packages.

param_range(prefix, range, vars = NULL)

param_glue(pattern, ..., vars = NULL)

Arguments

prefix, range

For param_range() only, prefix is a string naming a parameter and range is an integer vector providing the indices of a subset of elements to select. For example, using

  param_range("beta", c(1,2,8))

would select parameters named beta[1], beta[2], and beta[8]. param_range() is only designed for the case that the indices are integers surrounded by brackets. If there are no brackets use num_range().

vars

NULL or a character vector of parameter names to choose from. This is only needed for the atypical use case of calling the function as a standalone function outside of vars(), select(), etc. Typically this is left as NULL and will be set automatically for the user.

pattern, ...

For param_glue() only, pattern is a string containing expressions enclosed in braces and ... should be named arguments providing one character vector per expression in braces in patten. It is easiest to describe how to use these arguments with an example:

param_glue("beta_{var}[{level}]",
           var = c("age", "income"),
           level = c(3,8))

would select parameters with names "beta_age[3]", "beta_income[3]", "beta_age[8]", "beta_income[8]".

Details

As of version 1.7.0, bayesplot allows the pars argument for MCMC plots to use "tidy" variable selection (in the style of the dplyr package). The vars() function is re-exported from dplyr for this purpose.

Features of tidy selection includes direct selection (vars(alpha, sigma)), everything-but selection (vars(-alpha)), ranged selection (vars(`beta[1]`:`beta[3]`)), support for selection functions (vars(starts_with("beta"))), and combinations of these features. See the Examples section, below.

When using pars for tidy parameter selection, the regex_pars argument is ignored because bayesplot supports using tidyselect helper functions (starts_with(), contains(), num_range(), etc.) for the same purpose. bayesplot also exports some additional helper functions to help with parameter selection:

  • param_range(): like num_range() but used when parameter indexes are in brackets (e.g. beta[2]).

  • param_glue(): for more complicated parameter names with multiple indexes (including variable names) inside the brackets (e.g., beta[(Intercept) age_group:3]).

These functions can be used inside of vars(), dplyr::select(), and similar functions, just like the tidyselect helper functions.

Extra Advice

Parameter names in vars() are not quoted. When the names contain special characters like brackets, they should be wrapped in backticks, as in vars(`beta[1]`).

To exclude a range of variables, wrap the sequence in parentheses and then negate it. For example, (vars(-(`beta[1]`:`beta[3]`))) would exclude beta[1], beta[2], and beta[3].

vars() is a helper function. It holds onto the names and expressions used to select columns. When selecting variables inside a bayesplot function, use vars(...): mcmc_hist(data, pars = vars(alpha)). When using select() to prepare a dataframe for a bayesplot function, do not use vars(): data %>% select(alpha) %>% mcmc_hist().

Internally, tidy selection works by converting names and expressions into position numbers. As a result, integers will select parameters; vars(1, 3) selects the first and third ones. We do not endorse this approach because positions might change as variables are added and removed from models. To select a parameter that happens to be called 1, use backticks to escape it vars(`1`).

See also

Examples

x <- example_mcmc_draws(params = 6) dimnames(x)
#> $Iteration #> NULL #> #> $Chain #> [1] "chain:1" "chain:2" "chain:3" "chain:4" #> #> $Parameter #> [1] "alpha" "sigma" "beta[1]" "beta[2]" "beta[3]" "beta[4]" #>
mcmc_hex(x, pars = vars(alpha, `beta[2]`))
mcmc_dens(x, pars = vars(sigma, contains("beta")))
mcmc_hist(x, pars = vars(-contains("beta")))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
# using the param_range() helper mcmc_hist(x, pars = vars(param_range("beta", c(1, 3, 4))))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
############################# ## Examples using rstanarm ## ############################# if (requireNamespace("rstanarm", quietly = TRUE)) { # see ?rstanarm::example_model fit <- example("example_model", package = "rstanarm", local=TRUE)$value print(fit) posterior <- as.data.frame(fit) str(posterior) color_scheme_set("brightblue") mcmc_hist(posterior, pars = vars(size, contains("period"))) # same as previous but using dplyr::select() and piping library("dplyr") posterior %>% select(size, contains("period")) %>% mcmc_hist() mcmc_intervals(posterior, pars = vars(contains("herd"))) mcmc_intervals(posterior, pars = vars(contains("herd"), -contains("Sigma"))) bayesplot_theme_set(ggplot2::theme_dark()) color_scheme_set("viridisC") mcmc_areas_ridges(posterior, pars = vars(starts_with("b["))) bayesplot_theme_set() color_scheme_set("purple") not_789 <- vars(starts_with("b["), -matches("[7-9]")) mcmc_intervals(posterior, pars = not_789) # using the param_glue() helper just_149 <- vars(param_glue("b[(Intercept) herd:{level}]", level = c(1,4,9))) mcmc_intervals(posterior, pars = just_149) # same but using param_glue() with dplyr::select() # before passing to bayesplot posterior %>% select(param_glue("b[(Intercept) herd:{level}]", level = c(1, 4, 9))) %>% mcmc_intervals() }
#> #> exmpl_> example_model <- #> exmpl_+ stan_glmer(cbind(incidence, size - incidence) ~ size + period + (1|herd), #> exmpl_+ data = lme4::cbpp, family = binomial, QR = TRUE, #> exmpl_+ # this next line is only to keep the example small in size! #> exmpl_+ chains = 2, cores = 1, seed = 12345, iter = 500, refresh = 0)
#> Warning: Bulk Effective Samples Size (ESS) is too low, indicating posterior means and medians may be unreliable. #> Running the chains for more iterations may help. See #> http://mc-stan.org/misc/warnings.html#bulk-ess
#> #> exmpl_> example_model #> stan_glmer #> family: binomial [logit] #> formula: cbind(incidence, size - incidence) ~ size + period + (1 | herd) #> observations: 56 #> ------ #> Median MAD_SD #> (Intercept) -1.5 0.6 #> size 0.0 0.0 #> period2 -1.0 0.3 #> period3 -1.1 0.3 #> period4 -1.6 0.4 #> #> Error terms: #> Groups Name Std.Dev. #> herd (Intercept) 0.76 #> Num. levels: herd 15 #> #> ------ #> * For help interpreting the printed output see ?print.stanreg #> * For info on the priors used see ?prior_summary.stanreg #> stan_glmer #> family: binomial [logit] #> formula: cbind(incidence, size - incidence) ~ size + period + (1 | herd) #> observations: 56 #> ------ #> Median MAD_SD #> (Intercept) -1.5 0.6 #> size 0.0 0.0 #> period2 -1.0 0.3 #> period3 -1.1 0.3 #> period4 -1.6 0.4 #> #> Error terms: #> Groups Name Std.Dev. #> herd (Intercept) 0.76 #> Num. levels: herd 15 #> #> ------ #> * For help interpreting the printed output see ?print.stanreg #> * For info on the priors used see ?prior_summary.stanreg #> 'data.frame': 500 obs. of 21 variables: #> $ (Intercept) : num -1.18 -1.09 -0.43 -2.03 -1.48 ... #> $ size : num -1.90e-02 -1.58e-02 -4.95e-02 1.52e-02 5.28e-05 ... #> $ period2 : num -0.774 -0.882 -1.369 -0.647 -1.174 ... #> $ period3 : num -1.403 -1.377 -1.558 -0.993 -1.154 ... #> $ period4 : num -2.15 -2.02 -2.16 -1.01 -1.35 ... #> $ b[(Intercept) herd:1] : num 0.354 0.589 0.647 0.391 0.438 ... #> $ b[(Intercept) herd:2] : num -0.1974 0.0478 -0.2906 0.0599 0.1538 ... #> $ b[(Intercept) herd:3] : num 0.777 0.265 -0.139 0.312 0.241 ... #> $ b[(Intercept) herd:4] : num -0.193 -1.125 -0.209 0.129 0.459 ... #> $ b[(Intercept) herd:5] : num 0.39 -0.162 -0.134 0.16 0.203 ... #> $ b[(Intercept) herd:6] : num -0.3461 -0.0542 -0.2365 0.0969 0.2203 ... #> $ b[(Intercept) herd:7] : num 1.355 0.9721 0.2933 0.0976 0.1166 ... #> $ b[(Intercept) herd:8] : num 0.691 1.058 0.586 0.255 0.431 ... #> $ b[(Intercept) herd:9] : num -0.8868 -0.0291 -1.3847 0.3846 0.6979 ... #> $ b[(Intercept) herd:10] : num -0.433 -0.366 -0.549 -0.344 -0.649 ... #> $ b[(Intercept) herd:11] : num -0.1961 0.3954 0.3539 -0.0534 0.226 ... #> $ b[(Intercept) herd:12] : num 0.0441 -0.5955 -0.9077 -0.1648 -0.2372 ... #> $ b[(Intercept) herd:13] : num -0.548 -1.345 -0.544 -0.449 -0.469 ... #> $ b[(Intercept) herd:14] : num 1.697 0.905 1.21 0.75 1.284 ... #> $ b[(Intercept) herd:15] : num -0.597 -0.412 -0.507 -0.16 -0.253 ... #> $ Sigma[herd:(Intercept),(Intercept)]: num 0.254 0.341 0.385 0.122 0.216 ...
#> #> Attaching package: ‘dplyr’
#> The following object is masked from ‘package:testthat’: #> #> matches
#> The following objects are masked from ‘package:stats’: #> #> filter, lag
#> The following objects are masked from ‘package:base’: #> #> intersect, setdiff, setequal, union
################################### ## More examples of param_glue() ## ################################### library(dplyr) posterior <- tibble( b_Intercept = rnorm(1000), sd_condition__Intercept = rexp(1000), sigma = rexp(1000), `r_condition[A,Intercept]` = rnorm(1000), `r_condition[B,Intercept]` = rnorm(1000), `r_condition[C,Intercept]` = rnorm(1000), `r_condition[A,Slope]` = rnorm(1000), `r_condition[B,Slope]` = rnorm(1000) ) posterior
#> # A tibble: 1,000 x 8 #> b_Intercept sd_condition__I… sigma `r_condition[A,… `r_condition[B,… #> <dbl> <dbl> <dbl> <dbl> <dbl> #> 1 0.0806 0.0797 1.42 -0.0764 0.381 #> 2 0.859 1.10 0.0278 0.665 0.0754 #> 3 2.95 0.307 4.28 -1.07 1.96 #> 4 1.12 0.341 0.896 -0.120 0.622 #> 5 1.03 1.51 1.26 -1.05 -0.296 #> 6 -0.231 0.615 1.05 0.266 -1.45 #> 7 0.884 0.280 0.451 -0.347 0.281 #> 8 0.139 0.799 0.429 -0.818 -1.80 #> 9 0.269 1.94 1.14 0.225 0.411 #> 10 1.07 0.722 4.04 1.39 0.906 #> # … with 990 more rows, and 3 more variables: `r_condition[C,Intercept]` <dbl>, #> # `r_condition[A,Slope]` <dbl>, `r_condition[B,Slope]` <dbl>
# using one expression in braces posterior %>% select( param_glue("r_condition[{level},Intercept]", level = c("A", "B")) ) %>% mcmc_hist()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
# using multiple expressions in braces posterior %>% select( param_glue( "r_condition[{level},{type}]", level = c("A", "B"), type = c("Intercept", "Slope")) ) %>% mcmc_hist()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.