### Install tidybayes.rethinking from GitHub Source: https://mjskay.github.io/tidybayes.rethinking Install the devtools package if you don't have it, then install tidybayes.rethinking from GitHub. ```r install.packages("devtools") # only necessary if you don't have devtools already devtools::install_github("mjskay/tidybayes.rethinking") ``` -------------------------------- ### Install tidybayes Development Version from GitHub Source: https://mjskay.github.io/tidybayes/index.html Installs the latest development version of the tidybayes package from GitHub using the devtools package. ```R install.packages("devtools") devtools::install_github("mjskay/tidybayes") ``` -------------------------------- ### Example: Gather variables from tidy_draws and calculate median and QI Source: https://mjskay.github.io/tidybayes/reference/gather_variables.html This example shows how to use gather_variables with tidy_draws to reshape the data, followed by median_qi to compute median and quantile intervals. This is similar to ggmcmc::ggs. ```R # the first three lines below are roughly equivalent to ggmcmc::ggs(RankCorr) RankCorr %>% tidy_draws() %>% gather_variables() %>% median_qi() ``` -------------------------------- ### Create Example Dataset Source: https://mjskay.github.io/tidybayes/articles/tidybayes.html Generates a tibble with 5 conditions and 10 observations each, including random responses. This dataset is used to demonstrate tidybayes functionalities. ```R set.seed(5) n = 10 n_condition = 5 ABC = tibble( condition = factor(rep(c("A","B","C","D","E"), n)), response = rnorm(n * 5, c(0,1,2,1,-1), 0.5) ) ``` -------------------------------- ### Example: Gather variables and calculate median and QI Source: https://mjskay.github.io/tidybayes/reference/gather_variables.html This example demonstrates using gather_variables after spread_draws to reshape the data, then calculates the median and quantile interval for each variable. It requires dplyr and ggdist packages. ```R # \donttest{ library(dplyr) data(RankCorr, package = "ggdist") RankCorr %>% spread_draws(b[i,v], tau[i]) %>% gather_variables() %>% median_qi() ``` -------------------------------- ### Install tidybayes from CRAN Source: https://mjskay.github.io/tidybayes/index.html Installs the latest stable version of the tidybayes package from CRAN. ```R install.packages("tidybayes") ``` -------------------------------- ### Visualize Example Dataset Source: https://mjskay.github.io/tidybayes/articles/tidybayes.html Creates a scatter plot of the 'response' variable against 'condition' to visualize the distribution of data points. ```R ABC %>% ggplot(aes(x = response, y = fct_rev(condition))) + geom_point(alpha = 0.5) + ylab("condition") ``` -------------------------------- ### Example Dataset with Categorical Predictor Source: https://mjskay.github.io/tidybayes/reference/recover_types.html This example demonstrates creating a tibble with a categorical predictor variable that has multiple levels, which can then be used with `recover_types` to ensure correct type recovery. ```R # Here's an example dataset with a categorical predictor (`condition`) with several levels: set.seed(5) n = 10 n_condition = 5 ABC = tibble( condition = factor(rep(c("A","B","C","D","E"), n)), response = rnorm(n * 5, c(0,1,2,1,-1), 0.5) ) ``` -------------------------------- ### Load Required Libraries for Tidybayes Examples Source: https://mjskay.github.io/tidybayes/index.html Loads essential R libraries for data manipulation, visualization, and statistical modeling, commonly used with tidybayes. ```R library(magrittr) library(dplyr) library(ggplot2) library(rstan) library(tidybayes) library(emmeans) library(broom) library(brms) library(modelr) library(forcats) library(cowplot) library(RColorBrewer) library(gganimate) theme_set(theme_tidybayes() + panel_border()) ``` -------------------------------- ### Example: Extracting Draws from a Model Fit Source: https://mjskay.github.io/tidybayes/reference/tidy_draws.html This example demonstrates how to use `tidy_draws` to extract posterior draws from a model fit object. It requires the `coda` package for the `line` dataset and the `magrittr` package for the pipe operator. ```R library(magrittr) data(line, package = "coda") line %>% tidy_draws() ``` -------------------------------- ### emmeans contrast method example (eff) Source: https://mjskay.github.io/tidybayes/reference/emmeans_comparison.html Demonstrates the output of the 'eff' emmeans contrast method, which compares each level to the average of all levels. This matrix format is not directly usable by compare_levels. ```r emmeans:::eff.emmc(c("a","b","c","d")) ``` -------------------------------- ### Create Sample Dataset for Modeling Source: https://mjskay.github.io/tidybayes/index.html Generates a tibble named 'ABC' with 'condition' and 'response' variables, suitable for hierarchical modeling examples. Includes a basic ggplot visualization of the data. ```R set.seed(5) n = 10 n_condition = 5 ABC = tibble( condition = factor(rep(c("A","B","C","D","E"), n)), response = rnorm(n * 5, c(0,1,2,1,-1), 0.5) ) ABC %>% ggplot(aes(x = response, y = condition)) + geom_point(alpha = 0.5) + ylab("condition") ``` -------------------------------- ### R Example: Extracting and Summarizing Marginal Means Source: https://mjskay.github.io/tidybayes/reference/gather_emmeans_draws.html Demonstrates how to fit a brms model, calculate marginal means by condition using emmeans, and then extract and summarize the posterior draws using gather_emmeans_draws and median_qi. ```R # \dontrun{ library(dplyr) library(magrittr) library(brms) library(emmeans) #> Welcome to emmeans. # > Caution: You lose important information if you filter this package's results. # > See '? untidy' # Here's an example dataset with a categorical predictor (`condition`) with several levels: set.seed(5) n = 10 n_condition = 5 ABC = tibble( condition = rep(c("A","B","C","D","E"), n), response = rnorm(n * 5, c(0,1,2,1,-1), 0.5) ) m = brm(response ~ condition, data = ABC, # 1 chain / few iterations just so example runs quickly # do not use in practice chains = 1, iter = 500) #> Compiling Stan program... #> Start sampling #> #> SAMPLING FOR MODEL 'anon_model' NOW (CHAIN 1). #> Chain 1: #> Chain 1: Gradient evaluation took 5.3e-05 seconds #> Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0.53 seconds. #> Chain 1: Adjust your expectations accordingly! #> Chain 1: #> Chain 1: #> Chain 1: Iteration: 1 / 500 [ 0%] (Warmup) #> Chain 1: Iteration: 50 / 500 [ 10%] (Warmup) #> Chain 1: Iteration: 100 / 500 [ 20%] (Warmup) #> Chain 1: Iteration: 150 / 500 [ 30%] (Warmup) #> Chain 1: Iteration: 200 / 500 [ 40%] (Warmup) #> Chain 1: Iteration: 250 / 500 [ 50%] (Warmup) #> Chain 1: Iteration: 251 / 500 [ 50%] (Sampling) #> Chain 1: Iteration: 300 / 500 [ 60%] (Sampling) #> Chain 1: Iteration: 350 / 500 [ 70%] (Sampling) #> Chain 1: Iteration: 400 / 500 [ 80%] (Sampling) #> Chain 1: Iteration: 450 / 500 [ 90%] (Sampling) #> Chain 1: Iteration: 500 / 500 [100%] (Sampling) #> Chain 1: #> Chain 1: Elapsed Time: 0.012 seconds (Warm-up) #> Chain 1: 0.006 seconds (Sampling) #> Chain 1: 0.018 seconds (Total) #> Chain 1: # Once we've fit the model, we can use emmeans() (and functions # from that package) to get whatever marginal distributions we want. # For example, we can get marginal means by condition: m %>% emmeans(~ condition) %>% gather_emmeans_draws() %>% median_qi() #> # A tibble: 5 × 7 #> condition .value .lower .upper .width .point .interval #> #> 1 A 0.191 -0.128 0.542 0.95 median qi #> 2 B 1.02 0.685 1.35 0.95 median qi #> 3 C 1.87 1.54 2.21 0.95 median qi #> 4 D 1.03 0.683 1.37 0.95 median qi #> 5 E -0.948 -1.30 -0.584 0.95 median qi ``` -------------------------------- ### Example: Summarizing Draws Before and After combine_chains Source: https://mjskay.github.io/tidybayes/reference/combine_chains.html Demonstrates the effect of `combine_chains` on a tidy data frame of draws. The first summary shows the default `.chain` and `.iteration` columns, while the second shows the result after `combine_chains` has merged them into the `.draw` column. ```R library(magrittr) library(coda) data(line, package = "coda") # The `line` posterior has two chains with 200 iterations each: line %>% tidy_draws() %>% summary() #> #> .chain .iteration .draw alpha #> Min. :1.0 Min. : 1.00 Min. : 1.0 Min. :0.858 #> 1st Qu.:1.0 1st Qu.: 50.75 1st Qu.:100.8 1st Qu.:2.732 #> Median :1.5 Median :100.50 Median :200.5 Median :3.019 #> Mean :1.5 Mean :100.50 Mean :200.5 Mean :2.988 #> 3rd Qu.:2.0 3rd Qu.:150.25 3rd Qu.:300.2 3rd Qu.:3.242 #> Max. :2.0 Max. :200.00 Max. :400.0 Max. :7.173 #> beta sigma #> Min. :-1.5662 Min. : 0.3262 #> 1st Qu.: 0.6039 1st Qu.: 0.6158 #> Median : 0.7963 Median : 0.7912 #> Mean : 0.7992 Mean : 0.9681 #> 3rd Qu.: 0.9925 3rd Qu.: 1.0752 #> Max. : 1.8320 Max. :11.2331 # combine_chains combines the chain and iteration column into the .draw column. line %>% tidy_draws() %>% combine_chains() %>% summary() #> #> .chain .iteration .draw alpha #> Min. :1.0 Min. : 1.00 Min. : 1.0 Min. :0.858 #> 1st Qu.:1.0 1st Qu.: 50.75 1st Qu.:100.8 1st Qu.:2.732 #> Median :1.5 Median :100.50 Median :200.5 Median :3.019 #> Mean :1.5 Mean :100.50 Mean :200.5 Mean :2.988 #> 3rd Qu.:2.0 3rd Qu.:150.25 3rd Qu.:300.2 3rd Qu.:3.242 #> Max. :2.0 Max. :200.00 Max. :400.0 Max. :7.173 #> beta sigma #> Min. :-1.5662 Min. : 0.3262 #> 1st Qu.: 0.6039 1st Qu.: 0.6158 #> Median : 0.7963 Median : 0.7912 #> Mean : 0.7992 Mean : 0.9681 #> 3rd Qu.: 0.9925 3rd Qu.: 1.0752 #> Max. : 1.8320 Max. :11.2331 ``` -------------------------------- ### Generating Multimodal Draws for HDI Example Source: https://mjskay.github.io/tidybayes/articles/tidybayes.html This code snippet generates sample data from a multimodal normal mixture distribution, which is then used to demonstrate the behavior of `mode_hdi()`. ```R set.seed(123) multimodal_draws = tibble( x = c(rnorm(5000, 0, 1), rnorm(2500, 4, 1)) ) ``` -------------------------------- ### Example: Plotting Posterior Predictive Intervals with add_draws Source: https://mjskay.github.io/tidybayes/reference/add_draws.html This example demonstrates how to use `add_draws` with `posterior_epred` to plot posterior predictive intervals for a brms model. It requires `ggplot2`, `dplyr`, `brms`, and `modelr` packages. Note that this usage is roughly equivalent to `add_epred_draws` but lacks argument standardization across model types. ```r # \dontrun{ library(ggplot2) library(dplyr) #> #> Attaching package: 'dplyr' #> The following objects are masked from 'package:stats': #> #> filter, lag #> The following objects are masked from 'package:base': #> #> intersect, setdiff, setequal, union library(brms) #> Loading required package: Rcpp #> Loading 'brms' package (version 2.21.0). Useful instructions #> can be found by typing help('brms'). A more detailed introduction #> to the package is available through vignette('brms_overview'). #> #> Attaching package: 'brms' #> The following objects are masked from 'package:tidybayes': #> #> dstudent_t, pstudent_t, qstudent_t, rstudent_t #> The following object is masked from 'package:stats': #> #> ar library(modelr) theme_set(theme_light()) m_mpg = brm(mpg ~ hp * cyl, data = mtcars, # 1 chain / few iterations just so example runs quickly # do not use in practice chains = 1, iter = 500) #> Compiling Stan program... #> Start sampling #> #> SAMPLING FOR MODEL 'anon_model' NOW (CHAIN 1). #> Chain 1: #> Chain 1: Gradient evaluation took 3.7e-05 seconds #> Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0.37 seconds. #> Chain 1: Adjust your expectations accordingly! #> Chain 1: #> Chain 1: #> Chain 1: Iteration: 1 / 500 [ 0%] (Warmup) #> Chain 1: Iteration: 50 / 500 [ 10%] (Warmup) #> Chain 1: Iteration: 100 / 500 [ 20%] (Warmup) #> Chain 1: Iteration: 150 / 500 [ 30%] (Warmup) #> Chain 1: Iteration: 200 / 500 [ 40%] (Warmup) #> Chain 1: Iteration: 250 / 500 [ 50%] (Warmup) #> Chain 1: Iteration: 251 / 500 [ 50%] (Sampling) #> Chain 1: Iteration: 300 / 500 [ 60%] (Sampling) #> Chain 1: Iteration: 350 / 500 [ 70%] (Sampling) #> Chain 1: Iteration: 400 / 500 [ 80%] (Sampling) #> Chain 1: Iteration: 450 / 500 [ 90%] (Sampling) #> Chain 1: Iteration: 500 / 500 [100%] (Sampling) #> Chain 1: #> Chain 1: Elapsed Time: 0.187 seconds (Warm-up) #> Chain 1: 0.044 seconds (Sampling) #> Chain 1: 0.231 seconds (Total) #> Chain 1: #> 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 #> https://mc-stan.org/misc/warnings.html#bulk-ess #> Warning: Tail Effective Samples Size (ESS) is too low, indicating posterior variances and tail quantiles may be unreliable. #> Running the chains for more iterations may help. See #> https://mc-stan.org/misc/warnings.html#tail-ess # plot posterior predictive intervals mtcars %>% group_by(cyl) %>% data_grid(hp = seq_range(hp, n = 101)) %>% # the line below is roughly equivalent to add_epred_draws(m_mpg), except # that it does not standardize arguments across model types. add_draws(posterior_epred(m_mpg, newdata = .)) %>% ggplot(aes(x = hp, y = mpg, color = ordered(cyl))) + stat_lineribbon(aes(y = .value), alpha = 0.25) + geom_point(data = mtcars) + scale_fill_brewer(palette = "Greys") # } ``` -------------------------------- ### Basic Usage of gather_pairs for Scatterplot Matrix Source: https://mjskay.github.io/tidybayes/reference/gather_pairs.html Demonstrates how to use gather_pairs to create pairwise combinations for plotting. This example customizes output column names and generates a scatterplot matrix using ggplot2. ```R library(ggplot2) library(dplyr) t_a = rnorm(100) t_b = rnorm(100, t_a * 2) t_c = rnorm(100) df = rbind( data.frame(g = "a", t = t_a), data.frame(g = "b", t = t_b), data.frame(g = "c", t = t_c) ) df %>% gather_pairs(g, t, row = "g_row", col = "g_col", x = "t_x", y = "t_y") %>% ggplot(aes(t_x, t_y)) + geom_point() + facet_grid(vars(g_row), vars(g_col)) ``` -------------------------------- ### Plotting posterior predictive lines with sampled draws Source: https://mjskay.github.io/tidybayes/reference/sample_draws.html This example demonstrates how to use `sample_draws` to select a subset of posterior draws for plotting. It's recommended to use `sample_draws` for spaghetti plots, but for plotting intervals, it's best to use all available draws. ```R # \dontrun{ library(ggplot2) library(dplyr) library(brms) library(modelr) theme_set(theme_light()) m_mpg = brm(mpg ~ hp * cyl, data = mtcars, # 1 chain / few iterations just so example runs quickly # do not use in practice chains = 1, iter = 500) #> Compiling Stan program... #> Start sampling #> #> SAMPLING FOR MODEL 'anon_model' NOW (CHAIN 1). #> Chain 1: #> Chain 1: Gradient evaluation took 4e-05 seconds #> Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0.4 seconds. #> Chain 1: Adjust your expectations accordingly! #> Chain 1: #> Chain 1: #> Chain 1: Iteration: 1 / 500 [ 0%] (Warmup) #> Chain 1: Iteration: 50 / 500 [ 10%] (Warmup) #> Chain 1: Iteration: 100 / 500 [ 20%] (Warmup) #> Chain 1: Iteration: 150 / 500 [ 30%] (Warmup) #> Chain 1: Iteration: 200 / 500 [ 40%] (Warmup) #> Chain 1: Iteration: 250 / 500 [ 50%] (Warmup) #> Chain 1: Iteration: 251 / 500 [ 50%] (Sampling) #> Chain 1: Iteration: 300 / 500 [ 60%] (Sampling) #> Chain 1: Iteration: 350 / 500 [ 70%] (Sampling) #> Chain 1: Iteration: 400 / 500 [ 80%] (Sampling) #> Chain 1: Iteration: 450 / 500 [ 90%] (Sampling) #> Chain 1: Iteration: 500 / 500 [100%] (Sampling) #> Chain 1: #> Chain 1: Elapsed Time: 0.128 seconds (Warm-up) #> Chain 1: 0.045 seconds (Sampling) #> Chain 1: 0.173 seconds (Total) #> Chain 1: #> Warning: The largest R-hat is 1.07, indicating chains have not mixed. #> Running the chains for more iterations may help. See #> https://mc-stan.org/misc/warnings.html#r-hat #> 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 #> https://mc-stan.org/misc/warnings.html#bulk-ess #> Warning: Tail Effective Samples Size (ESS) is too low, indicating posterior variances and tail quantiles may be unreliable. #> Running the chains for more iterations may help. See #> https://mc-stan.org/misc/warnings.html#tail-ess # draw 100 fit lines from the posterior and overplot them mtcars %>% group_by(cyl) %>% data_grid(hp = seq_range(hp, n = 101)) %>% add_epred_draws(m_mpg) %>% # NOTE: only use sample_draws here when making spaghetti plots; for # plotting intervals it is always best to use all draws sample_draws(100) %>% ggplot(aes(x = hp, y = mpg, color = ordered(cyl))) + geom_line(aes(y = .epred, group = paste(cyl, .draw)), alpha = 0.25) + geom_point(data = mtcars) # } ``` -------------------------------- ### Explicitly specify column for median_qi with grouped data Source: https://mjskay.github.io/tidybayes/articles/tidybayes.html This is a more verbose equivalent to the previous example. It explicitly groups by `condition` (though `spread_draws` does this automatically) and then applies `median_qi` to the `condition_mean` column. ```R m %>% spread_draws(condition_mean[condition]) %>% group_by(condition) %>% median_qi(condition_mean) ``` -------------------------------- ### Compose Nested Data with x_at_y Source: https://mjskay.github.io/tidybayes/reference/x_at_y.html Use x_at_y to create a nested index for 'site' based on 'plot'. This example demonstrates turning a site identifier into a nested index where each plot maps to its corresponding site. ```R library(magrittr) df = data.frame( plot = factor(paste0("p", rep(1:8, times = 2))), site = factor(paste0("s", rep(1:4, each = 2, times = 2))) ) # turns site into a nested index: site[p] gives the site for plot p df %>% compose_data(site = x_at_y(site, plot)) ``` -------------------------------- ### Annotating Densities with stat_halfeye and fill aesthetic Source: https://mjskay.github.io/tidybayes/articles/tidybayes.html The fill aesthetic in stat_halfeye can vary within a slab to annotate specific regions, such as a region of practical equivalence (ROPE). This example annotates the ROPE with a different color. ```R m %>% spread_draws(condition_mean[condition]) %>% ggplot(aes(y = fct_rev(condition), x = condition_mean, fill = after_stat(abs(x) < .8))) + stat_halfeye() + geom_vline(xintercept = c(-.8, .8), linetype = "dashed") + scale_fill_manual(values = c("gray80", "skyblue")) ``` -------------------------------- ### Animated Hypothetical Outcome Plots (HOPs) Source: https://mjskay.github.io/tidybayes/articles/tidy-brms.html Create animated hypothetical outcome plots (HOPs) of fit lines. This example uses a small number of draws for demonstration purposes. ```r set.seed(123456) # NOTE: using a small number of draws to keep this example ``` -------------------------------- ### Fitting a Stan Model with tidybayes Source: https://mjskay.github.io/tidybayes/reference/recover_types.html Fits a Stan model using the `stan()` function and prepares data using `compose_data()`. Control parameters for adaptation are set, and the number of chains and iterations are reduced for a quick example. ```r m = stan(model_code = stan_code, data = compose_data(ABC), control = list(adapt_delta=0.99), # 1 chain / few iterations just so example runs quickly # do not use in practice chains = 1, iter = 500) ``` -------------------------------- ### Plotting Summarized Intervals with geom_pointinterval Source: https://mjskay.github.io/tidybayes/articles/tidybayes.html This example demonstrates plotting summarized posterior intervals using geom_pointinterval. The linewidth aesthetic is mapped to -.width, so smaller probability intervals appear as thicker lines. This mapping is a default in geom_pointinterval when a .width column is present. ```R m %>% spread_draws(condition_mean[condition]) %>% median_qi(.width = c(.95, .66)) %>% ggplot(aes( y = fct_rev(condition), x = condition_mean, xmin = .lower, xmax = .upper, # size = -.width means smaller probability interval => thicker line # this can be omitted, geom_pointinterval includes it automatically # if a .width column is in the input data. linewidth = -.width )) + geom_pointinterval() ``` -------------------------------- ### Get convergence diagnostics using summarise_draws Source: https://mjskay.github.io/tidybayes/articles/tidybayes.html Use `tidybayes::summarise_draws()` on grouped data frames to quickly obtain convergence diagnostics such as mean, median, sd, MAD, quantiles, Rhat, and effective sample sizes. ```R m %>% spread_draws(condition_mean[condition]) %>% summarise_draws() ``` -------------------------------- ### Basic Usage of compare_levels Source: https://mjskay.github.io/tidybayes/reference/compare_levels.html Demonstrates a basic application of compare_levels with default settings, using the RankCorr dataset. ```R library(dplyr) library(ggplot2) data(RankCorr, package = "ggdist") # Example usage (assuming RankCorr is structured appropriately): # compare_levels(RankCorr, variable = corr, by = method) %>% # ggplot(aes(x = variable, y = value, color = by)) + # stat_halfeye() ``` -------------------------------- ### Extracting posteriors Source: https://mjskay.github.io/tidybayes/reference/index.html Functions to get tidy draws or rvars of posterior distributions from objects, with helper functions for examining objects. ```APIDOC ## get_variables() ### Description Get the names of the variables in a fitted Bayesian model. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## recover_types() ### Description Decorate a model fit or sample with data types recovered from the input data. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## gather_draws() / spread_draws() ### Description Extract draws of variables in a Bayesian model fit into a tidy data format. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## tidy_draws() ### Description Get a sample of posterior draws from a model as a tibble. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## gather_emmeans_draws() ### Description Extract a tidy data frame of draws of posterior distributions of "estimated marginal means" (emmeans/lsmeans) from a Bayesian model fit. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## ungather_draws() / unspread_draws() ### Description Turn tidy data frames of variables from a Bayesian model back into untidy data. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## gather_rvars() / spread_rvars() ### Description Extract draws from a Bayesian model into tidy data frames of random variables. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## nest_rvars() / unnest_rvars() ### Description Nest and unnest `rvar` columns in data frames. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## summarise_draws(__) ### Description Summaries of draws in `grouped_df` objects. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` -------------------------------- ### Gather emmeans Pairwise Contrasts and Summarize Source: https://mjskay.github.io/tidybayes/articles/tidybayes.html Perform pairwise comparisons using `emmeans::contrast()` and then convert the results to a tidy format with `gather_emmeans_draws()`. Summarize the contrasts using `median_qi()`. ```R m_rst %>% emmeans::emmeans( ~ condition) %>% emmeans::contrast(method = "pairwise") %>% gather_emmeans_draws() %>% median_qi() ``` -------------------------------- ### Customize Index Variable Prefix Source: https://mjskay.github.io/tidybayes/reference/compose_data.html Customize the prefix for dimension index variables using the `.n_name` argument with `n_prefix()`. This example uses 'N' as the prefix. ```R library(magrittr) df = data.frame( plot = factor(paste0("p", rep(1:8, times = 2))), site = factor(paste0("s", rep(1:4, each = 2, times = 2))) ) # you can use n_prefix() to define a different prefix (e.g. "N"): df %>% compose_data(.n_name = n_prefix("N")) ``` -------------------------------- ### Create a sample tidy dataset Source: https://mjskay.github.io/tidybayes/articles/tidy-rstanarm.html Generates a tibble named 'ABC' with 50 observations across five conditions, simulating a typical tidy data format for use in modeling. ```R set.seed(5) n = 10 n_condition = 5 ABC = tibble( condition = rep(c("A","B","C","D","E"), n), response = rnorm(n * 5, c(0,1,2,1,-1), 0.5) ) ``` -------------------------------- ### Get model variable names from rstanarm fit Source: https://mjskay.github.io/tidybayes/articles/tidy-rstanarm.html Retrieves a list of all variable names available for extraction from the fitted rstanarm model object 'm'. ```R get_variables(m) ``` -------------------------------- ### Add Predicted Probabilities (Matrix Format) Source: https://mjskay.github.io/tidybayes/articles/tidy-posterior.html Uses add_epred_rvars to get predictions from the ordinal model. The output for '.epred' is a matrix where columns represent probabilities for each category. ```r tibble(mpg = c(21,22)) %>% add_epred_rvars(m_cyl) ``` -------------------------------- ### Gather draws and summarize Source: https://mjskay.github.io/tidybayes/reference/spread_draws.html Demonstrates gathering draws for multiple parameters ('tau[i]', 'typical_r') into a long format using gather_draws, followed by summarizing them with median_qi to calculate the median and credible interval. ```r RankCorr %>% gather_draws(tau[i], typical_r) %>% median_qi() #> # A tibble: 4 × 8 #> i .variable .value .lower .upper .width .point .interval #> #> 1 1 tau 6.03 5.03 7.11 0.95 median qi #> 2 2 tau 3.30 2.41 4.46 0.95 median qi #> 3 3 tau 3.65 2.73 4.72 0.95 median qi #> 4 NA typical_r 0.548 0.309 0.778 0.95 median qi ``` -------------------------------- ### Plotting Posterior Predictive Intervals Source: https://mjskay.github.io/tidybayes/articles/tidy-posterior.html Use add_predicted_rvars() to get draws from the posterior predictive distribution and ggdist::stat_interval() to plot predictive bands alongside the data. ```r ABC %>$ data_grid(condition) %>$ add_predicted_rvars(m) %>$ ggplot(aes(y = condition)) + stat_interval(aes(xdist = .prediction), .width = c(.50, .80, .95, .99)) + geom_point(aes(x = response), data = ABC) + scale_color_brewer() ``` -------------------------------- ### Equivalent stat_lineribbon Implementation Source: https://mjskay.github.io/tidybayes/index.html This code block shows a manual implementation of stat_lineribbon using stat_summary for ribbons and lines, demonstrating how to plot median and quantile intervals. ```R stat_summary( aes(y = .prediction, fill = forcats::fct_rev(ordered(after_stat(.width))), group = -after_stat(.width)), geom = "ribbon", point_interval = median_qi, fun.args = list(.width = c(.99, .95, .8, .5)) ) + stat_summary(aes(y = .prediction), fun.y = median, geom = "line", color = "red", linewidth = 1.25) ``` -------------------------------- ### Get convergence diagnostics for indexed variables Source: https://mjskay.github.io/tidybayes/articles/tidy-rstanarm.html Use summarise_draws to quickly obtain convergence diagnostics for indexed variables. This function is implemented for grouped data frames. ```r m %>% spread_draws(b[,group]) %>% summarise_draws() ``` -------------------------------- ### Extracting fits, predictions, and residuals Source: https://mjskay.github.io/tidybayes/reference/index.html Functions to get tidy draws or rvars from transformed linear predictors (“fits”), posterior predictions, or residuals. ```APIDOC ## add_epred_draws() / epred_draws() ### Description Add draws from the posterior fit of a model to a data frame. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## add_linpred_draws() / linpred_draws() ### Description Add draws from the posterior linear predictor of a model to a data frame. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## add_predicted_draws() / predicted_draws() ### Description Add posterior predictive draws from a model to a data frame. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## add_residual_draws() / residual_draws() ### Description Add draws from the posterior residuals of a model to a data frame. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## add_draws() ### Description Add draws to a data frame in tidy format. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## add_epred_rvars() / epred_rvars() ### Description Add `rvar`s for the posterior expectation of a model to a data frame. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## add_linpred_rvars() / linpred_rvars() ### Description Add `rvar`s for the posterior linear predictor of a model to a data frame. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` ```APIDOC ## add_predicted_rvars() / predicted_rvars() ### Description Add `rvar`s for the posterior predictive of a model to a data frame. ### Parameters (No parameters explicitly documented in the source) ### Request Example (No request example provided in the source) ### Response (No response details provided in the source) ``` -------------------------------- ### data_list Function Source: https://mjskay.github.io/tidybayes/reference/data_list.html Creates a list with class `c("data_list", "list")`, similar to the base `list()` function. ```APIDOC ## data_list(...) ### Description Creates a list with class `c("data_list", "list")` instead of `c("list")`, but largely otherwise acts like the `list()` function. ### Arguments Additional arguments passed to `list()`. ### Value An object of class `c("data_list", "list")`. ``` -------------------------------- ### Load required R libraries Source: https://mjskay.github.io/tidybayes/articles/tidy-brms.html Loads all necessary libraries for data manipulation, visualization, and Bayesian modeling. Sets a custom tidybayes theme. ```r library(magrittr) library(dplyr) library(purrr) library(forcats) library(tidyr) library(modelr) library(ggdist) library(tidybayes) library(ggplot2) library(cowplot) library(rstan) library(brms) library(ggrepel) library(RColorBrewer) library(gganimate) library(posterior) library(distributional) theme_set(theme_tidybayes() + panel_border()) ``` -------------------------------- ### Basic usage of spread_rvars and gather_rvars Source: https://mjskay.github.io/tidybayes/reference/spread_rvars.html Demonstrates the basic syntax for extracting variables with specified dimensions using `spread_rvars` and `gather_rvars`. ```R spread_rvars(model, a[i], b[i,v]) ``` ```R gather_rvars(model, a[i], b[i,v]) ``` -------------------------------- ### Generate Nested Indices with x_at_y Source: https://mjskay.github.io/tidybayes/reference/compose_data.html Use `x_at_y()` within `compose_data` to generate nested indices, useful for models with hierarchical structures. This example creates a 'site' index specific to each 'plot'. ```R library(magrittr) df = data.frame( plot = factor(paste0("p", rep(1:8, times = 2))), site = factor(paste0("s", rep(1:4, each = 2, times = 2))) ) # If you have nesting, you may want a nested index, which can be generated using x_at_y() # Here, site[p] will give the site for plot p df %>% compose_data(site = x_at_y(site, plot)) ``` -------------------------------- ### Display the first 10 rows of the sample dataset Source: https://mjskay.github.io/tidybayes/articles/tidy-rstanarm.html Prints the first 10 rows of the 'ABC' tibble to show its structure and sample data. ```R head(ABC, 10) ``` -------------------------------- ### Display ideal model summary Source: https://mjskay.github.io/tidybayes/articles/tidybayes-residuals.html Prints a summary of the fitted 'm_ideal' model, showing estimated coefficients, uncertainty, and convergence diagnostics. ```R m_ideal ``` -------------------------------- ### Visualize posterior predictions with posterior means Source: https://mjskay.github.io/tidybayes/articles/tidybayes.html Combine posterior predictions and posterior distributions of means for visualization. Use `spread_draws` to get draws, `mutate` for predictions, and `ggplot2` with `stat_interval` and `stat_pointinterval`. ```R draws = m %>% spread_draws(condition_mean[condition], response_sd) reps = draws %>% mutate(y_rep = rnorm(n(), condition_mean, response_sd)) ABC %>% ggplot(aes(y = condition)) + stat_interval(aes(x = y_rep), .width = c(.95, .8, .5), data = reps) + stat_pointinterval(aes(x = condition_mean), .width = c(.95, .66), position = position_nudge(y = -0.3), data = draws) + geom_point(aes(x = response)) + scale_color_brewer() ``` -------------------------------- ### ggplot2 Density Plot with Customizations Source: https://mjskay.github.io/tidybayes/reference/density_bins.html Demonstrates creating a density plot using ggplot2 with custom aesthetics like shape, fill, and alpha. Includes warnings about dplyr version compatibility. ```r geom_point(aes(x = hp, y = mpg, fill = ordered(cyl)), shape = 21, data = mtcars) + scale_alpha_continuous(range = c(0, 1)) + scale_fill_brewer(palette = "Set2") #> Warning: Returning more (or less) than 1 row per `summarise()` group was deprecated in #> dplyr 1.1.0. #> ℹ Please use `reframe()` instead. #> ℹ When switching from `summarise()` to `reframe()`, remember that `reframe()` #> always returns an ungrouped data frame and adjust accordingly. ``` -------------------------------- ### Get model variables for ordinal regression Source: https://mjskay.github.io/tidybayes/articles/tidy-rstanarm.html Retrieves the names of all variables (coefficients and thresholds) from a fitted rstanarm ordinal regression model. Useful for understanding model structure and parameter names. ```R get_variables(m_esoph_rs) ``` -------------------------------- ### Plotting intervals with multiple probability levels Source: https://mjskay.github.io/tidybayes/articles/tidy-brms.html Demonstrates how to generate multiple probability intervals (e.g., 95%, 80%, 50%) using the `.width` argument in `median_qi()`. This facilitates comparing intervals of different widths. ```R m %>% spread_draws(b_Intercept, r_condition[condition,]) %>% median_qi(condition_mean = b_Intercept + r_condition, .width = c(.95, .8, .5)) ``` -------------------------------- ### Mutate after spreading rvars Source: https://mjskay.github.io/tidybayes/articles/tidy-posterior.html After spreading rvars, use dplyr's mutate to perform calculations on the combined variables. This example calculates the mean within each condition by summing the intercept and condition effect. ```r m %> spread_rvars(`b_Intercept`, r_condition[condition,Intercept]) %> mutate(condition_mean = b_Intercept + r_condition) ``` -------------------------------- ### Summarize Posteriors with median_qi() Source: https://mjskay.github.io/tidybayes/index.html Use median_qi() from ggdist to obtain tidy output of point summaries and quantile intervals for posterior distributions. This function is part of the point_interval family. ```R m %>% spread_draws(condition_mean[condition]) %>% median_qi(condition_mean) ```