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.

packages <- 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")

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.

devtools::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")

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

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

Version 0.2.0.

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

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:

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,
  title = {Statistical rethinking with brms, ggplot2, and the tidyverse: {{Second}} edition},
  author = {Kurz, A. Solomon},
  year = {2023},
  month = {jan},
  edition = {version 0.4.0},
  url = {https://bookdown.org/content/4857/}
}

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

Baumer, B. S., Kaplan, D. T., & Horton, N. J. (2021). Modern data science with R (2nd edition). Taylor & Francis Group, LLC. https://mdsr-book.github.io/mdsr2e/
Bryan, J., the STAT 545 TAs, & Hester, J. (2020). Happy Git and GitHub for the useR. https://happygitwithr.com
Bürkner, P.-C. (2017). brms: An R package for Bayesian multilevel models using Stan. Journal of Statistical Software, 80(1), 1–28. https://doi.org/10.18637/jss.v080.i01
Bürkner, P.-C. (2018). Advanced Bayesian multilevel modeling with the R package brms. The R Journal, 10(1), 395–411. https://doi.org/10.32614/RJ-2018-017
Bürkner, P.-C. (2022j). brms: Bayesian regression models using ’Stan. https://CRAN.R-project.org/package=brms
Gelman, A., Hill, J., & Vehtari, A. (2020). Regression and other stories. Cambridge University Press. https://doi.org/10.1017/9781139161879
Gohel, D. (2022). flextable: Functions for tabular reporting [Manual]. https://CRAN.R-project.org/package=flextable
Grolemund, G., & Wickham, H. (2017). R for data science. O’Reilly. https://r4ds.had.co.nz
Healy, K. (2018). Data visualization: A practical introduction. Princeton University Press. https://socviz.co/
McElreath, R. (2020a). Statistical rethinking: A Bayesian course with examples in R and Stan (Second Edition). CRC Press. https://xcelab.net/rm/statistical-rethinking/
Navarro, D. (2019). Learning statistics with R. https://learningstatisticswithr.com
Peng, R. D. (2022). R programming for data science. https://bookdown.org/rdpeng/rprogdatascience/
R Core Team. (2022). R: A language and environment for statistical computing. R Foundation for Statistical Computing. https://www.R-project.org/
Roback, P., & Legler, J. (2021). Beyond multiple linear regression: Applied generalized linear models and multilevel models in R. CRC Press. https://bookdown.org/roback/bookdown-BeyondMLR/
Robinson, D., Hayes, A., & Couch, S. (2022). broom: Convert statistical objects into tidy tibbles [Manual]. https://CRAN.R-project.org/package=broom
Wickham, H. (2016). ggplot2: Elegant graphics for data analysis. Springer-Verlag New York. https://ggplot2-book.org/
Wickham, H. (2020). The tidyverse style guide. https://style.tidyverse.org/
Wickham, H. (2022). tidyverse: Easily install and load the ’tidyverse’. https://CRAN.R-project.org/package=tidyverse
Wickham, H., Averick, M., Bryan, J., Chang, W., McGowan, L. D., François, R., Grolemund, G., Hayes, A., Henry, L., Hester, J., Kuhn, M., Pedersen, T. L., Miller, E., Bache, S. M., Müller, K., Ooms, J., Robinson, D., Seidel, D. P., Spinu, V., … Yutani, H. (2019). Welcome to the tidyverse. Journal of Open Source Software, 4(43), 1686. https://doi.org/10.21105/joss.01686
Wilke, C. O. (2019). Fundamentals of data visualization. https://clauswilke.com/dataviz/
Xie, Y. (2022). bookdown: Authoring books and technical documents with R Markdown. https://CRAN.R-project.org/package=bookdown
Xie, Y., Allaire, J. J., & Grolemund, G. (2020). R markdown: The definitive guide. Chapman and Hall/CRC. https://bookdown.org/yihui/rmarkdown/