d <- posterior::example_draws()
library(posterior)
#> Warning: package 'posterior' was built under R version 4.6.1
#> This is posterior version 1.7.1
#>
#> Attaching package: 'posterior'
#> The following objects are masked from 'package:stats':
#>
#> mad, sd, var
#> The following objects are masked from 'package:base':
#>
#> %in%, match
# Port of select() that works with `draws_df` objects
select_variables <- function(x, ...) {
rlang::check_installed("tidyselect", "for tidyselect variable selection")
UseMethod("select_variables")
}
select_variables.draws <- function(x, ...) {
nms <- stats::setNames(variables(x), variables(x))
pos <- tidyselect::eval_select(
rlang::expr(c(...)),
nms,
# to do
allow_rename = FALSE
)
subset_draws(x, variable = nms[pos], scalar = TRUE)
}
d |> as_draws_df() |> select_variables(mu)
#> # A draws_df: 100 iterations, 4 chains, and 1 variables
#> mu
#> 1 2.01
#> 2 1.46
#> 3 5.81
#> 4 6.85
#> 5 1.81
#> 6 3.84
#> 7 5.47
#> 8 1.20
#> 9 0.15
#> 10 7.17
#> # ... with 390 more draws
#> # ... hidden reserved variables {'.chain', '.iteration', '.draw'}
d |> select_variables(mu, starts_with("theta")) |> dimnames()
#> $iteration
#> [1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12"
#> [13] "13" "14" "15" "16" "17" "18" "19" "20" "21" "22" "23" "24"
#> [25] "25" "26" "27" "28" "29" "30" "31" "32" "33" "34" "35" "36"
#> [37] "37" "38" "39" "40" "41" "42" "43" "44" "45" "46" "47" "48"
#> [49] "49" "50" "51" "52" "53" "54" "55" "56" "57" "58" "59" "60"
#> [61] "61" "62" "63" "64" "65" "66" "67" "68" "69" "70" "71" "72"
#> [73] "73" "74" "75" "76" "77" "78" "79" "80" "81" "82" "83" "84"
#> [85] "85" "86" "87" "88" "89" "90" "91" "92" "93" "94" "95" "96"
#> [97] "97" "98" "99" "100"
#>
#> $chain
#> [1] "1" "2" "3" "4"
#>
#> $variable
#> [1] "mu" "theta[1]" "theta[2]" "theta[3]" "theta[4]" "theta[5]" "theta[6]"
#> [8] "theta[7]" "theta[8]"
d |> select_variables(mu, `theta[1]`) |> dimnames()
#> $iteration
#> [1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12"
#> [13] "13" "14" "15" "16" "17" "18" "19" "20" "21" "22" "23" "24"
#> [25] "25" "26" "27" "28" "29" "30" "31" "32" "33" "34" "35" "36"
#> [37] "37" "38" "39" "40" "41" "42" "43" "44" "45" "46" "47" "48"
#> [49] "49" "50" "51" "52" "53" "54" "55" "56" "57" "58" "59" "60"
#> [61] "61" "62" "63" "64" "65" "66" "67" "68" "69" "70" "71" "72"
#> [73] "73" "74" "75" "76" "77" "78" "79" "80" "81" "82" "83" "84"
#> [85] "85" "86" "87" "88" "89" "90" "91" "92" "93" "94" "95" "96"
#> [97] "97" "98" "99" "100"
#>
#> $chain
#> [1] "1" "2" "3" "4"
#>
#> $variable
#> [1] "mu" "theta[1]"
# Should fail ----------
d |> select_variables(mu, theta) |> dimnames()
#> Error in `select_variables()`:
#> ! Can't select columns that don't exist.
#> ✖ Column `theta` doesn't exist.Created on 2026-09-16 with reprex v2.1.1