{"id":13400786,"url":"https://github.com/paul-buerkner/brms","last_synced_at":"2025-05-14T11:08:43.373Z","repository":{"id":37335944,"uuid":"37606896","full_name":"paul-buerkner/brms","owner":"paul-buerkner","description":"brms R package for Bayesian generalized multivariate non-linear multilevel models using Stan","archived":false,"fork":false,"pushed_at":"2025-05-05T07:53:00.000Z","size":273533,"stargazers_count":1316,"open_issues_count":122,"forks_count":194,"subscribers_count":38,"default_branch":"master","last_synced_at":"2025-05-05T08:35:47.684Z","etag":null,"topics":["bayesian-inference","brms","multilevel-models","r-package","stan","statistical-models"],"latest_commit_sha":null,"homepage":"https://paulbuerkner.com/brms/","language":"R","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/paul-buerkner.png","metadata":{"files":{"readme":"README.Rmd","changelog":"NEWS.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"paul-buerkner"}},"created_at":"2015-06-17T16:29:31.000Z","updated_at":"2025-05-05T07:53:03.000Z","dependencies_parsed_at":"2023-02-19T16:01:42.565Z","dependency_job_id":"70cfce09-f726-4095-8893-f36acc034994","html_url":"https://github.com/paul-buerkner/brms","commit_stats":{"total_commits":4950,"total_committers":46,"mean_commits":107.6086956521739,"dds":0.06848484848484848,"last_synced_commit":"931107bb97d992f434af93f02fa16125c5cdb7a3"},"previous_names":[],"tags_count":56,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paul-buerkner%2Fbrms","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paul-buerkner%2Fbrms/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paul-buerkner%2Fbrms/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paul-buerkner%2Fbrms/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/paul-buerkner","download_url":"https://codeload.github.com/paul-buerkner/brms/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254129481,"owners_count":22019628,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bayesian-inference","brms","multilevel-models","r-package","stan","statistical-models"],"created_at":"2024-07-30T19:00:55.456Z","updated_at":"2025-05-14T11:08:43.351Z","avatar_url":"https://github.com/paul-buerkner.png","language":"R","funding_links":["https://github.com/sponsors/paul-buerkner"],"categories":["R","Software/packages","Clinical Development"],"sub_categories":["Specific","Pharmacokinetics (PK) \u0026 Pharmacodynamics (PD)"],"readme":"---\noutput:\n  md_document:\n    variant: markdown_github\n---\n\n\u003c!-- README.md is generated from README.Rmd. Please edit that file --\u003e\n\n```{r, include=FALSE}\nstopifnot(require(knitr))\noptions(width = 90)\nknitr::opts_chunk$set(\n  collapse = TRUE,\n  comment = \"#\u003e\",\n  fig.path = \"man/figures/README-\",\n  dev = \"png\",\n  dpi = 150,\n  fig.asp = 0.8,\n  fig.width = 5,\n  out.width = \"60%\",\n  fig.align = \"center\"\n)\nlibrary(brms)\nggplot2::theme_set(bayesplot::theme_default())\nset.seed(1234)\n```\n\n\u003cimg src=\"man/figures/brms.png\" width = 120 alt=\"brms Logo\"/\u003e[\u003cimg src=\"https://raw.githubusercontent.com/stan-dev/logos/master/logo_tm.png\" align=\"right\" width=120 alt=\"Stan Logo\"/\u003e](https://mc-stan.org/)\n\n# brms\n\n[![R-CMD-check](https://github.com/paul-buerkner/brms/workflows/R-CMD-check/badge.svg)](https://github.com/paul-buerkner/brms/actions)\n[![Coverage Status](https://codecov.io/github/paul-buerkner/brms/coverage.svg?branch=master)](https://app.codecov.io/github/paul-buerkner/brms?branch=master)\n[![CRAN Version](https://www.r-pkg.org/badges/version/brms)](https://cran.r-project.org/package=brms)\n[![Downloads](https://cranlogs.r-pkg.org/badges/brms?color=brightgreen)](https://CRAN.R-project.org/package=brms)\n\n\n## Overview\n\nThe **brms** package provides an interface to fit Bayesian generalized\n(non-)linear multivariate multilevel models using Stan, which is a C++ package\nfor performing full Bayesian inference (see https://mc-stan.org/). The formula\nsyntax is very similar to that of the package lme4 to provide a familiar and\nsimple interface for performing regression analyses. A wide range of response\ndistributions are supported, allowing users to fit -- among others -- linear,\nrobust linear, count data, survival, response times, ordinal, zero-inflated, and\neven self-defined mixture models all in a multilevel context. Further modeling\noptions include non-linear and smooth terms, auto-correlation structures,\ncensored data, missing value imputation, and quite a few more. In addition, all\nparameters of the response distribution can be predicted in order to perform\ndistributional regression. Multivariate models (i.e., models with multiple\nresponse variables) can be fit, as well. Prior specifications are flexible and\nexplicitly encourage users to apply prior distributions that actually reflect\ntheir beliefs. Model fit can easily be assessed and compared with posterior\npredictive checks, cross-validation, and Bayes factors.\n\n## Resources\n\n* [Introduction to brms](https://doi.org/10.18637/jss.v080.i01) (Journal of Statistical Software)\n* [Advanced multilevel modeling with brms](https://journal.r-project.org/archive/2018/RJ-2018-017/index.html) (The R Journal)\n* [Website](https://paulbuerkner.com/brms/) (Website of brms with documentation and vignettes)\n* [Blog posts](http://paulbuerkner.com/software/brms-blogposts.html) (List of blog posts about brms)\n* [Ask a question](https://discourse.mc-stan.org/) (Stan Forums on Discourse)\n* [Open an issue](https://github.com/paul-buerkner/brms/issues) (GitHub issues for bug reports and feature requests)\n\n##  How to use brms\n\n```{r load, message=FALSE}\nlibrary(brms)\n```\n\nAs a simple example, we use poisson regression to model the seizure counts in\nepileptic patients to investigate whether the treatment (represented by variable\n`Trt`) can reduce the seizure counts and whether the effect of the treatment\nvaries with the (standardized) baseline number of seizures a person had before\ntreatment (variable `zBase`). As we have multiple observations per person, a\ngroup-level intercept is incorporated to account for the resulting dependency in\nthe data.\n\n```{r fit1, results='hide', message=FALSE}\nfit1 \u003c- brm(count ~ zAge + zBase * Trt + (1|patient),\n            data = epilepsy, family = poisson())\n```\n\nThe results (i.e., posterior draws) can be investigated using\n\n```{r summary}\nsummary(fit1)\n```\n\nOn the top of the output, some general information on the model is given, such\nas family, formula, number of iterations and chains. Next, group-level effects\nare displayed separately for each grouping factor in terms of standard\ndeviations and (in case of more than one group-level effect per grouping factor;\nnot displayed here) correlations between group-level effects. On the bottom of\nthe output, population-level effects (i.e. regression coefficients) are\ndisplayed. If incorporated, autocorrelation effects and family specific\nparameters (e.g., the residual standard deviation 'sigma' in normal models) are\nalso given.\n\nIn general, every parameter is summarized using the mean ('Estimate') and the\nstandard deviation ('Est.Error') of the posterior distribution as well as\ntwo-sided 95% credible intervals ('l-95% CI' and 'u-95% CI') based on quantiles.\nWe see that the coefficient of `Trt` is negative with a zero overlapping\n95\\%-CI. This indicates that, on average, the treatment may reduce seizure\ncounts by some amount but the evidence based on the data and applied model is\nnot very strong and still insufficient by standard decision rules. Further, we\nfind little evidence that the treatment effect varies with the baseline number\nof seizures.\n\nThe last three values ('ESS_bulk', 'ESS_tail', and 'Rhat') provide information\non how well the algorithm could estimate the posterior distribution of this\nparameter. If 'Rhat' is considerably greater than 1, the algorithm has not yet\nconverged and it is necessary to run more iterations and / or set stronger\npriors.\n\nTo visually investigate the chains as well as the posterior distributions, we\ncan use the `plot` method. If we just want to see results of the regression\ncoefficients of `Trt` and `zBase`, we go for\n\n```{r plot}\nplot(fit1, variable = c(\"b_Trt1\", \"b_zBase\"))\n```\n\nA more detailed investigation can be performed by running\n`launch_shinystan(fit1)`. To better understand the relationship of the\npredictors with the response, I recommend the `conditional_effects` method:\n\n```{r conditional_effects}\nplot(conditional_effects(fit1, effects = \"zBase:Trt\"))\n```\n\nThis method uses some prediction functionality behind the scenes, which can also\nbe called directly. Suppose that we want to predict responses (i.e. seizure\ncounts) of a person in the treatment group (`Trt = 1`) and in the control group\n(`Trt = 0`) with average age and average number of previous seizures. Than we\ncan use\n\n```{r predict}\nnewdata \u003c- data.frame(Trt = c(0, 1), zAge = 0, zBase = 0)\npredict(fit1, newdata = newdata, re_formula = NA)\n```\n\nWe need to set `re_formula = NA` in order not to condition of the group-level\neffects. While the `predict` method returns predictions of the responses, the\n`fitted` method returns predictions of the regression line.\n\n```{r fitted}\nfitted(fit1, newdata = newdata, re_formula = NA)\n```\n\nBoth methods return the same estimate (up to random error), while the latter has\nsmaller variance, because the uncertainty in the regression line is smaller than\nthe uncertainty in each response. If we want to predict values of the original\ndata, we can just leave the `newdata` argument empty.\n\nSuppose, we want to investigate whether there is overdispersion in the model,\nthat is residual variation not accounted for by the response distribution. For\nthis purpose, we include a second group-level intercept that captures possible\noverdispersion.\n\n```{r fit2, results='hide', message=FALSE}\nfit2 \u003c- brm(count ~ zAge + zBase * Trt + (1|patient) + (1|obs),\n            data = epilepsy, family = poisson())\n```\n\nWe can then go ahead and compare both models via approximate leave-one-out (LOO)\ncross-validation.\n\n```{r loo, warning=FALSE}\nloo(fit1, fit2)\n```\n\nThe `loo` output when comparing models is a little verbose. We first see the\nindividual LOO summaries of the two models and then the comparison between them.\nSince higher `elpd` (i.e., expected log posterior density) values indicate\nbetter fit, we see that the model accounting for overdispersion (i.e., `fit2`)\nfits substantially better. However, we also see in the individual LOO outputs\nthat there are several problematic observations for which the approximations may\nhave not have been very accurate. To deal with this appropriately, we need to fall\nback to other methods such as `reloo` or `kfold` but this requires the model to\nbe refit several times which takes too long for the purpose of a quick example.\nThe post-processing methods we have shown above are just the tip of the\niceberg. For a full list of methods to apply on fitted model objects, type\n`methods(class = \"brmsfit\")`.\n\n## Citing brms and related software\n\nDeveloping and maintaining open source software is an important yet often\nunderappreciated contribution to scientific progress. Thus, whenever you are\nusing open source software (or software in general), please make sure to cite it\nappropriately so that developers get credit for their work.\n\nWhen using brms, please cite one or more of the following publications:\n\n- Bürkner P. C. (2017). brms: An R Package for Bayesian Multilevel Models\n  using Stan. *Journal of Statistical Software*. 80(1), 1-28.\n  doi.org/10.18637/jss.v080.i01\n- Bürkner P. C. (2018). Advanced Bayesian Multilevel Modeling with the R\n  Package brms. *The R Journal*. 10(1), 395-411. doi.org/10.32614/RJ-2018-017\n- Bürkner P. C. (2021). Bayesian Item Response Modeling in R with brms and Stan. \n  *Journal of Statistical Software*, 100(5), 1-54. doi.org/10.18637/jss.v100.i05\n\nAs brms is a high-level interface to Stan, please additionally cite Stan\n(see also https://mc-stan.org/users/citations/):\n\n- Stan Development Team. YEAR. Stan Modeling Language Users Guide and Reference \n  Manual, VERSION. https://mc-stan.org\n- Carpenter B., Gelman A., Hoffman M. D., Lee D., Goodrich B., Betancourt M.,\n  Brubaker M., Guo J., Li P., and Riddell A. (2017). Stan: A probabilistic\n  programming language. *Journal of Statistical Software*. 76(1).\n  doi.org/10.18637/jss.v076.i01\n\nFurther, brms relies on several other R packages and, of course, on R itself. To\nfind out how to cite R and its packages, use the `citation` function. There are\nsome features of brms which specifically rely on certain packages. The **rstan**\npackage together with **Rcpp** makes Stan conveniently accessible in R.\nVisualizations and posterior-predictive checks are based on **bayesplot** and\n**ggplot2**. Approximate leave-one-out cross-validation using `loo` and related\nmethods is done via the **loo** package. Marginal likelihood based methods such\nas `bayes_factor` are realized by means of the **bridgesampling** package.\nSplines specified via the `s` and `t2` functions rely on **mgcv**. If you use\nsome of these features, please also consider citing the related packages.\n\n## FAQ\n\n### How do I install brms?\n\nTo install the latest release version from CRAN use\n\n```{r install_brms, eval=FALSE}\ninstall.packages(\"brms\")\n```\n\nThe current developmental version can be downloaded from GitHub via\n\n```{r install_brms2, eval=FALSE}\nif (!requireNamespace(\"remotes\")) {\n  install.packages(\"remotes\")\n}\nremotes::install_github(\"paul-buerkner/brms\")\n```\n\nBecause brms is based on Stan, a C++ compiler is required. The program Rtools\n(available on https://cran.r-project.org/bin/windows/Rtools/) comes with a C++\ncompiler for Windows. On Mac, you should install Xcode. For further instructions\non how to get the compilers running, see the prerequisites section on\nhttps://github.com/stan-dev/rstan/wiki/RStan-Getting-Started.\n\n### I am new to brms. Where can I start?\n\nDetailed instructions and case studies are given in the package's extensive\nvignettes. See `vignette(package = \"brms\")` for an overview. For documentation\non formula syntax, families, and prior distributions see `help(\"brm\")`.\n\n### Where do I ask questions, propose a new feature, or report a bug?\n\nQuestions can be asked on the [Stan forums](https://discourse.mc-stan.org/) on\nDiscourse. To propose a new feature or report a bug, please open an issue on\n[GitHub](https://github.com/paul-buerkner/brms).\n\n### How can I extract the generated Stan code?\n\nIf you have already fitted a model, apply the `stancode` method on the\nfitted model object. If you just want to generate the Stan code without any\nmodel fitting, use the `stancode` method on your model formula.\n\n### Can I avoid compiling models?\n\nWhen you fit your model for the first time with brms, there is currently no way\nto avoid compilation. However, if you have already fitted your model and want to\nrun it again, for instance with more draws, you can do this without\nrecompilation by using the `update` method. For more details see\n`help(\"update.brmsfit\")`.\n\n### What is the difference between brms and rstanarm?\n\nThe rstanarm package is similar to brms in that it also allows to fit regression\nmodels using Stan for the backend estimation. Contrary to brms, rstanarm comes\nwith precompiled code to save the compilation time (and the need for a C++\ncompiler) when fitting a model. However, as brms generates its Stan code on the\nfly, it offers much more flexibility in model specification than rstanarm. Also,\nmultilevel models are currently fitted a bit more efficiently in brms. For\ndetailed comparisons of brms with other common R packages implementing\nmultilevel models, see `vignette(\"brms_multilevel\")` and\n`vignette(\"brms_overview\")`.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpaul-buerkner%2Fbrms","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpaul-buerkner%2Fbrms","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpaul-buerkner%2Fbrms/lists"}