*Statistical rethinking* with brms, ggplot2, and the tidyverse: Second edition

*version 0.4.0*

*2023-01-26*

# What and why

This ebook is based on the second edition of Richard McElreath’s (2020a) text, *Statistical rethinking: A Bayesian course with examples in R and Stan*. My contributions show how to fit the models he covered with Paul Bürkner’s **brms** package (Bürkner, 2017, 2018, 2022j), which makes it easy to fit Bayesian regression models in **R** (R Core Team, 2022) using Hamiltonian Monte Carlo. I also prefer plotting and data wrangling with the packages from the **tidyverse** (Wickham et al., 2019; Wickham, 2022). So we’ll be using those methods, too.

Are you looking for the companion ebook for McElreath’s 1st edition? Click here.

## My assumptions about you

If you’re looking at this project, I’m guessing you’re either a graduate student, a post-graduate academic or a researcher of some sort, which suggests you have at least a 101-level foundation in statistics. If you’re rusty, consider checking out the free text books by Roback and Legler (2021) or Navarro (2019) before diving into *Statistical rethinking*. I’m also assuming you understand the rudiments of **R** and have at least a vague idea about what the **tidyverse** is. If you’re totally new to **R**, consider starting with Peng’s (2022) *R programming for data science*. For an introduction to the **tidyvese**-style of data analysis, the best source I’ve found is Grolemund and Wickham’s (2017) *R for data science* (*R4DS*), which I extensively link to throughout this project. Another nice alternative is Baumer, Kaplan, and Horton’s (2021), *Modern data science with R*.

However, you do not need to be totally fluent in statistics or **R**. Otherwise why would you need this project, anyway? IMO, the most important things are curiosity, a willingness to try, and persistent tinkering. I love this stuff. Hopefully you will, too.

## How to use and understand this project

This project is not meant to stand alone. It’s a supplement to the second edition of McElreath’s text. I follow the structure of his text, chapter by chapter, translating his analyses into **brms** and **tidyverse**-style code. However, some of the sections in the text are composed entirely of equations or prose, leaving us nothing to translate. When we run into those sections, the corresponding sections in this project will sometimes be blank or omitted, though I do highlight some of the important points in quotes and prose of my own. So I imagine students might reference this project as they progress through McElreath’s text. I also imagine working data analysts might use this project in conjunction with the text as they flip to the specific sections that seem relevant to solving their data challenges.

I reproduce the bulk of the figures in the text, too. The plots in the first few chapters are the closest to those in the text. However, I’m passionate about data visualization and like to play around with color palettes, formatting templates, and other conventions quite a bit. As a result, the plots in each chapter have their own look and feel. For more on some of these topics, check out chapters 3, 7, and 28 in *R4DS*; Healy’s (2018) *Data visualization: A practical introduction*; Wilke’s (2019) *Fundamentals of data visualization*; or Wickham’s (2016) *ggplot2: Elegant graphics for data analysis*.

In this project, I use a handful of formatting conventions gleaned from *R4DS*, *The tidyverse style guide* (Wickham, 2020), and *R markdown: The definitive guide* (Xie et al., 2020).

**R**code blocks and their output appear in a gray background. E.g.,

`2 + 2 == 5`

`## [1] FALSE`

**R**and the names of specific package (e.g.,**brms**) are in**boldface**font.- Functions are in a typewriter font and followed by parentheses, all atop a gray background (e.g.,
`brm()`

). - When I want to make explicit the package a given function comes from, I insert the double-colon operator
`::`

between the package name and the function (e.g.,`tidybayes::median_qi()`

). **R**objects, such as data or function arguments, are in typewriter font atop gray backgrounds (e.g.,`chimpanzees`

,`.width = .5`

).- You can detect hyperlinks by their typical blue-colored font.
- In the text, McElreath indexed his models with names like
`m4.1`

(i.e., the first model of Chapter 4). I primarily followed that convention, but replaced the`m`

with a`b`

to stand for the**brms**package.

**R** setup

To get the full benefit from this ebook, you’ll need some software. Happily, everything will be free (provided you have access to a decent personal computer and an good internet connection).

First, you’ll need to install **R**, which you can learn about at https://cran.r-project.org/.

Though not necessary, your **R** experience might be more enjoyable if done through the free RStudio interface, which you can learn about at https://rstudio.com/products/rstudio/.

Once you have installed **R**, execute the following to install the bulk of the add-on packages. This will probably take a few minutes to finish. Go make yourself a coffee.

```
<- c("ape", "bayesplot", "brms", "broom", "dagitty", "devtools", "flextable", "GGally", "ggdag", "ggdark", "ggmcmc", "ggrepel", "ggthemes", "ggtree", "ghibli", "gtools", "invgamma", "loo", "patchwork", "posterior", "psych", "rcartocolor", "Rcpp", "remotes", "rstan", "santoku", "StanHeaders", "statebins", "tidybayes", "tidyverse", "viridis", "viridisLite", "wesanderson")
packages
install.packages(packages, dependencies = T)
```

A few of the other packages are not officially available via the Comprehensive R Archive Network (CRAN; https://cran.r-project.org/). You can download them directly from GitHub by executing the following.

```
::install_github("stan-dev/cmdstanr")
devtools::install_github("EdwinTh/dutchmasters")
devtools::install_github("gadenbuie/ggpomological")
devtools::install_github("GuangchuangYu/ggtree")
devtools::install_github("rmcelreath/rethinking")
devtools::install_github("UrbanInstitute/urbnmapr") devtools
```

It’s possible you’ll have problems installing some of these packages. Here are some likely suspects and where you can find help:

- for difficulties installing
**brms**, go to https://github.com/paul-buerkner/brms#how-do-i-install-brms or search around in the**brms**section of the Stan forums; - for difficulties installing
**cmdstanr**, go to https://mc-stan.org/cmdstanr/articles/cmdstanr.html; - for difficulties installing
**rethinking**, go to https://github.com/rmcelreath/rethinking#installation; and - for difficulties installing
**rstan**, go to https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started.

## We have updates

For a brief rundown of the version history, we have:

### Version 0.1.0.

I released the 0.1.0 version of this project in November 24, 2020. It was the first full-length and nearly complete draft including material from all the 17 chapters in McElreath’s source material. All **brms** models were fit with version 2.14.0+.

### Version 0.1.1.

On December 2, 2020, I released a mini update designed to

- fix code breaks resulting from updates to the
**broom**package (Robinson et al., 2022), caught by Jenny Bigman; - replace the soon-to-be retired
`sample_n()`

code with`slice_sample()`

, caught by Randall Pruim; - and correct a few typos along the way.

### Version 0.2.0.

On March 16, 2021, I released version 0.2.0, which included the following major improvements:

- a corrected workflow for fitting single-level b-spline models (Section 4.5.2), thanks to Stephen Wild;
- a refined workflow for fitting multilevel b-spline models using the
`s()`

function (Section 4.6), thanks to Gavin Simpson; - a new bonus section (4.7) on grouping predictors within matrix columns, thanks to insights from Gelman et al. (2020) and hints from Paul-Christian Bürkner;
- a
**brms**solution to the \(\sigma = 0.01\) sixth-order polynomial model in Section 7.1.1, thanks again to Stephen Wild; - a workflow to reproduce the Metropolis simulation for Figure 9.3, thanks to James Henegan;
- a corrected workflow for taking
`fitted()`

-based random draws for the bonus material in Section 13.5.2.1, thanks to an exchange with Ladislas Nalborczyk; - a
**brms**solution to McElreath’s bivariate differential equation model in Section 16.4, thanks to Markus Gesmann; - better use of
`geom_area()`

throughout the book, thanks to insights from Randall Pruim; - the adoption of a CONTRIBUTING section on GitHub, thanks to Brenton M. Wiernik;
- improved table workflow with the
**flextable**package (Gohel, 2022); and - all models have been refit using
**brms**version 2.15.0.

### Version 0.3.0.

On September 28, 2022, I released version 0.3.0, which included the following major improvements:

- an
`as_draws_df()`

-oriented workflow to replace the depreciated`posterior_samples()`

function; - better sampling in models in the first few due to changes in the
`ub`

argument; - more use of the uniform prior for \(\sigma\) to better match the text, thanks to the improved
`ub`

argument; - a more
**tidyverse**-oriented version of the`sim_happiness()`

function in Section 6.3, thanks to Randall Pruim - a more accurate depiction of entropy in Figure 10.2.b in Section 10.1.1, thanks to help from Hamed Bastan-Hagh,
- a cross link to the first edition, thanks to a suggestion from Will Petry;
- some corrected typos and updates to the links and citations; and
- all models have been refit using
**brms**version 2.18.0.

### Version 0.4.0.

Welcome to version 0.4.0! Noteworthy changes include:

- replacing my incorrect use of
`tidyr::expand()`

with a more appropriate`tidyr::expand_grid()`

workflow, thanks to insights from Desislava Petkova; - adopting the new
`linewidth`

argument for several**ggplot2**geoms (see here); and - minor prose, hyperlink, and code edits throughout.

### We’re not done yet and I could use your help.

Some areas of the book could use some fleshing out. The sections I’m particularly anxious to improve are

- 15.3, which may someday include a
**brms**workflow for categorical missing data; and - 16.2.3, which contains a mixture model that McElreath fit directly in Stan and I suspect may be possible in
**brms**with a custom likelihood.

If you have insights on how to improve these or any other sections, please share your thoughts on GitHub at https://github.com/ASKurz/Statistical_Rethinking_with_brms_ggplot2_and_the_tidyverse_2_ed/issues. The contribution guidelines for this book are listed at https://github.com/ASKurz/Statistical_Rethinking_with_brms_ggplot2_and_the_tidyverse_2_ed/blob/master/CONTRIBUTING.md.

## Thank-you’s are in order

I’d like to thank the following for their helpful contributions:

- E. David Aja (@edavidaja),
- Monica Alexander (@MJAlexander),
- Shaan Amin (@Shaan-Amin),
- Malcolm Barrett (@malcolmbarrett),
- Hamed Bastan-Hagh (@hamedbh),
- Adam Bear (@adambear91),
- Jenny Bigman (@jennybigman),
- Louis Bliard (@lbiard),
- Philipp Boersch-Supan (@pboesu),
- Paul-Christian Bürkner (@paul-buerkner),
- Damien Croteau-Chonka (@dcroteau-chonka),
- Markus Gesmann (@mages),
- James Henegan (@jameshenegan),
- Mathieu Jones (@00mathieu),
- William Lai (@williamlai2),
- Sebastian Lobentanzer (@slobentanzer),
- Ed Merkle (@ecmerkle),
- Ladislas Nalborczyk (@lnalborczyk),
- Desislava Petkova (@dipetkov),
- Will Petry (@wpetry),
- Randall Pruim (@rpruim),
- Gavin Simpson (@gavinsimpson),
- Kathleen Sprouffske (@sprouffske)
- Richard Torkar (@torkar),
- Brenton M. Wiernik (@bwiernik),
- Stephen Wild (@sjwild), and
- Donald R. Williams (@donaldRwilliams).

Science is better when we work together.

## License and citation

This book is licensed under the Creative Commons Zero v1.0 Universal license. You can learn the details, here. In short, you can use my work. Just make sure you give me the appropriate credit the same way you would for any other scholarly resource. Here’s the citation information:

```
@book{kurzStatisticalRethinkingSecondEd2023,
= {Statistical rethinking with brms, ggplot2, and the tidyverse: {{Second}} edition},
title = {Kurz, A. Solomon},
author = {2023},
year = {jan},
month = {version 0.4.0},
edition = {https://bookdown.org/content/4857/}
url }
```

## You can do this, too

This project is powered by Yihui Xie’s (2022) **bookdown** package, which makes it easy to turn R markdown files into HTML, PDF, and EPUB. Go here to learn more about bookdown. While you’re at it, also check out Xie, Allaire, and Grolemund’s *R markdown: The definitive guide*. And if you’re unacquainted with GitHub, check out Jenny Bryan’s (2020) *Happy Git and GitHub for the useR*. I’ve even blogged about what it was like putting together the first version of this project.

The source code of the project is available on GitHub at https://github.com/ASKurz/Statistical_Rethinking_with_brms_ggplot2_and_the_tidyverse_2_ed.

### References

*Modern data science with R*(2nd edition). Taylor & Francis Group, LLC. https://mdsr-book.github.io/mdsr2e/

*Happy Git and GitHub for the useR*. https://happygitwithr.com

*Journal of Statistical Software*,

*80*(1), 1–28. https://doi.org/10.18637/jss.v080.i01

*The R Journal*,

*10*(1), 395–411. https://doi.org/10.32614/RJ-2018-017

*brms: Bayesian regression models using ’Stan’*. https://CRAN.R-project.org/package=brms

*Regression and other stories*. Cambridge University Press. https://doi.org/10.1017/9781139161879

*flextable: Functions for tabular reporting*[Manual]. https://CRAN.R-project.org/package=flextable

*Data visualization: A practical introduction*. Princeton University Press. https://socviz.co/

*Statistical rethinking: A Bayesian course with examples in R and Stan*(Second Edition). CRC Press. https://xcelab.net/rm/statistical-rethinking/

*R programming for data science*. https://bookdown.org/rdpeng/rprogdatascience/

*R: A language and environment for statistical computing*. R Foundation for Statistical Computing. https://www.R-project.org/

*Beyond multiple linear regression: Applied generalized linear models and multilevel models in R*. CRC Press. https://bookdown.org/roback/bookdown-BeyondMLR/

*broom: Convert statistical objects into tidy tibbles*[Manual]. https://CRAN.R-project.org/package=broom

*ggplot2: Elegant graphics for data analysis*. Springer-Verlag New York. https://ggplot2-book.org/

*The tidyverse style guide*. https://style.tidyverse.org/

*tidyverse: Easily install and load the ’tidyverse’*. https://CRAN.R-project.org/package=tidyverse

*Journal of Open Source Software*,

*4*(43), 1686. https://doi.org/10.21105/joss.01686

*Fundamentals of data visualization*. https://clauswilke.com/dataviz/

*bookdown: Authoring books and technical documents with R Markdown*. https://CRAN.R-project.org/package=bookdown

*R markdown: The definitive guide*. Chapman and Hall/CRC. https://bookdown.org/yihui/rmarkdown/