{"id":14068873,"url":"https://github.com/stan-dev/posterior","last_synced_at":"2025-04-04T10:07:27.264Z","repository":{"id":42163847,"uuid":"212145446","full_name":"stan-dev/posterior","owner":"stan-dev","description":"The posterior R package","archived":false,"fork":false,"pushed_at":"2024-10-07T02:45:26.000Z","size":4227,"stargazers_count":167,"open_issues_count":67,"forks_count":23,"subscribers_count":14,"default_branch":"master","last_synced_at":"2024-10-29T14:21:57.031Z","etag":null,"topics":["bayes","bayesian","mcmc","r-package"],"latest_commit_sha":null,"homepage":"https://mc-stan.org/posterior/","language":"R","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/stan-dev.png","metadata":{"files":{"readme":"README.Rmd","changelog":"NEWS.md","contributing":".github/CONTRIBUTING.md","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},"funding":{"github":"stan-dev","custom":"https://mc-stan.org/support/"}},"created_at":"2019-10-01T16:30:28.000Z","updated_at":"2024-10-23T17:54:10.000Z","dependencies_parsed_at":"2023-10-29T13:20:06.226Z","dependency_job_id":"f7d661ca-dcd6-45a1-aa64-764f1ab1098c","html_url":"https://github.com/stan-dev/posterior","commit_stats":{"total_commits":985,"total_committers":17,"mean_commits":57.94117647058823,"dds":0.6700507614213198,"last_synced_commit":"90a07cce51fdde484e97596cdd186adf265d8f5e"},"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stan-dev%2Fposterior","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stan-dev%2Fposterior/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stan-dev%2Fposterior/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stan-dev%2Fposterior/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/stan-dev","download_url":"https://codeload.github.com/stan-dev/posterior/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246970249,"owners_count":20862510,"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":["bayes","bayesian","mcmc","r-package"],"created_at":"2024-08-13T07:06:27.447Z","updated_at":"2025-04-04T10:07:27.241Z","avatar_url":"https://github.com/stan-dev.png","language":"R","funding_links":["https://github.com/sponsors/stan-dev","https://mc-stan.org/support/"],"categories":["R"],"sub_categories":[],"readme":"---\noutput: github_document\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)\n```\n\n# posterior \u003cimg src=\"man/figures/stanlogo.png\" align=\"right\" width=\"120\" /\u003e\n\n\u003c!-- badges: start --\u003e\n[![CRAN\nstatus](https://www.r-pkg.org/badges/version/posterior)](https://CRAN.R-project.org/package=posterior)\n[![R-CMD-check](https://github.com/stan-dev/posterior/workflows/R-CMD-check/badge.svg)](https://github.com/stan-dev/posterior/actions?workflow=R-CMD-check)\n[![Coverage\nStatus](https://codecov.io/gh/stan-dev/posterior/branch/master/graph/badge.svg)](https://app.codecov.io/gh/stan-dev/posterior)\n\u003c!-- badges: end --\u003e\n\n\nThe **posterior** R package is intended to provide useful tools for both users\nand developers of packages for fitting Bayesian models or working with output\nfrom Bayesian models. The primary goals of the package are to:\n\n* Efficiently convert between many different useful formats of\n  draws (samples) from posterior or prior distributions.\n* Provide consistent methods for operations commonly performed on draws, \n  for example, subsetting, binding, or mutating draws.\n* Provide various summaries of draws in convenient formats.\n* Provide lightweight implementations of state of the art posterior inference \n  diagnostics.\n  \nIf you are new to **posterior** we recommend starting with these vignettes: \n\n* [*The posterior R package*](https://mc-stan.org/posterior/articles/posterior.html): \nan introduction to the package and its main functionality \n* [*rvar: The Random Variable Datatype*](https://mc-stan.org/posterior/articles/rvar.html): \nan overview of the new random variable datatype\n\n### Installation\n\nYou can install the latest official release version via\n\n```{r install_cran, eval=FALSE}\ninstall.packages(\"posterior\")\n```\n\nor build the developmental version directly from GitHub via\n\n```{r install_github, eval=FALSE}\n# install.packages(\"remotes\")\nremotes::install_github(\"stan-dev/posterior\")\n```\n\n### Examples\n\nHere we offer a few examples of using the package. For a more detailed overview\nsee the vignette [*The posterior R package*](https://mc-stan.org/posterior/articles/posterior.html).\n\n```{r load}\nlibrary(\"posterior\")\n```\n\nTo demonstrate how to work with the **posterior** package, we will use example\nposterior draws obtained from the eight schools hierarchical meta-analysis model\ndescribed in Gelman et al. (2013). Essentially, we have an estimate per school\n(`theta[1]` through `theta[8]`) as well as an overall mean (`mu`) and standard\ndeviation across schools (`tau`).\n\n#### Draws formats \n\n```{r draws_array}\neight_schools_array \u003c- example_draws(\"eight_schools\")\nprint(eight_schools_array, max_variables = 3)\n```\n\nThe draws for this example come as a `draws_array` object, that is, an array\nwith dimensions iterations x chains x variables. We can easily transform it to\nanother format, for instance, a data frame with additional meta information.\n\n```{r draws_df}\neight_schools_df \u003c- as_draws_df(eight_schools_array)\nprint(eight_schools_df)\n```\n\nDifferent formats are preferable in different situations and hence posterior\nsupports multiple formats and easy conversion between them. For more details on\nthe available formats see `help(\"draws\")`. All of the formats are essentially\nbase R object classes and can be used as such. For example, a `draws_matrix`\nobject is just a `matrix` with a little more consistency and additional methods.\n\n#### Summarizing draws\n\nComputing summaries of posterior or prior draws and convergence diagnostics for\nposterior draws is one of the most common tasks when working with Bayesian\nmodels fit using Markov Chain Monte Carlo (MCMC) methods. The **posterior**\npackage provides a flexible interface for this purpose via `summarise_draws()`:\n\n```{r summary}\n# summarise_draws or summarize_draws\nsummarise_draws(eight_schools_df)\n```\n\nBasically, we get a data frame with one row per variable and one column per\nsummary statistic or convergence diagnostic. The summaries `rhat`, `ess_bulk`,\nand `ess_tail` are described in Vehtari et al. (2020). We can choose which\nsummaries to compute by passing additional arguments, either functions or names\nof functions. For instance, if we only wanted the mean and its corresponding\nMonte Carlo Standard Error (MCSE) we would use:\n\n```{r summary-with-measures}\nsummarise_draws(eight_schools_df, \"mean\", \"mcse_mean\")\n```\n\nFor a function to work with `summarise_draws`, it needs to take a vector or\nmatrix of numeric values and returns a single numeric value or a named vector of\nnumeric values.\n\n#### Subsetting draws \n\nAnother common task when working with posterior (or prior) draws, is subsetting\naccording to various aspects of the draws (iterations, chains, or variables).\n**posterior** provides a convenient interface for this purpose via the\n`subset_draws()` method. For example, here is the code to extract the first five \niterations of the first two chains of the variable `mu`:\n\n```{r subset}\nsubset_draws(eight_schools_df, variable = \"mu\", chain = 1:2, iteration = 1:5)\n```\n\nThe same call to `subset_draws()` can be used regardless of whether the object \nis a `draws_df`, `draws_array`, `draws_list`, etc.\n\n#### Mutating and renaming draws\n\nThe magic of having obtained draws from the joint posterior (or prior)\ndistribution of a set of variables is that these draws can also be used\nto obtain draws from any other variable that is a function of the original variables.\nThat is, if are interested in the posterior distribution of, say, \n`phi = (mu + tau)^2` all we have to do is to perform the transformation for each\nof the individual draws to obtain draws from the posterior distribution of the\ntransformed variable. This procedure is automated in the `mutate_variables` method:\n\n```{r}\nx \u003c- mutate_variables(eight_schools_df, phi = (mu + tau)^2)\nx \u003c- subset_draws(x, c(\"mu\", \"tau\", \"phi\"))\nprint(x)\n```\n\nWhen we do the math ourselves, we see that indeed for each draw, \n`phi` is equal to `(mu + tau)^2` (up to rounding two 2 digits \nfor the purpose of printing).\n\nWe may also easily rename variables, or even entire vectors of variables via\n`rename_variables`, for example:\n\n```{r}\nx \u003c- rename_variables(eight_schools_df, mean = mu, alpha = theta)\nvariables(x)\n```\n\nAs with all **posterior** methods, `mutate_variables` and `rename_variables` \ncan be used with all draws formats.\n\n#### Binding draws together\n\nSuppose we have multiple draws objects that we want to bind together:\n\n```{r}\nx1 \u003c- draws_matrix(alpha = rnorm(5), beta = 1)\nx2 \u003c- draws_matrix(alpha = rnorm(5), beta = 2)\nx3 \u003c- draws_matrix(theta = rexp(5))\n```\n\nThen, we can use the `bind_draws` method to bind them along different dimensions.\nFor example, we can bind `x1` and `x3` together along the `'variable'` dimension:\n\n```{r}\nx4 \u003c- bind_draws(x1, x3, along = \"variable\")\nprint(x4)\n```\n\nOr, we can bind `x1` and `x2` together along the `'draw'` dimension:\n\n```{r}\nx5 \u003c- bind_draws(x1, x2, along = \"draw\")\nprint(x5)\n```\n\nAs with all **posterior** methods, `bind_draws` can be used with all draws \nformats.\n\n#### Converting from regular R objects to draws formats\n\nThe `eight_schools` example already comes in a format natively supported by\nposterior but we could of course also import the draws from other sources,\nfor example, from common base R objects:\n\n```{r draws_matrix}\nx \u003c- matrix(rnorm(50), nrow = 10, ncol = 5)\ncolnames(x) \u003c- paste0(\"V\", 1:5)\nx \u003c- as_draws_matrix(x)\nprint(x)\n\nsummarise_draws(x, \"mean\", \"sd\", \"median\", \"mad\")\n```\n\nInstead of `as_draws_matrix()` we also could have just used `as_draws()`, which\nattempts to find the closest available format to the input object. In this case\nthis would result in a `draws_matrix` object either way.\n\nThe above matrix example contained only one chain. Multi-chain draws could be \nstored in base R 3-D array object, which can also be converted to a draws object:\n\n```{r}\nx \u003c- array(data=rnorm(200), dim=c(10, 2, 5))\nx \u003c- as_draws_matrix(x)\nvariables(x) \u003c-  paste0(\"V\", 1:5)\nprint(x)\n```\n\n#### Converting from mcmc objects to draws formats\n\nThe **coda** and **rjags** packages use `mcmc` and `mcmc.list` objects which \ncan also be converted to draws objects:\n\n```{r}\ndata(line, package = \"coda\")\nline \u003c- as_draws_df(line)\nprint(line)\n```\n\n### Contributing to posterior\n\nWe welcome contributions!\nThe **posterior** package is under active development.\nIf you find bugs or have ideas for new features (for us or yourself to\nimplement) please [open an issue](https://github.com/stan-dev/posterior/issues) on GitHub.\nSee [CONTRIBUTING.md](https://github.com/stan-dev/posterior/blob/master/.github/CONTRIBUTING.md)\nfor more details.\n\n### Citing posterior\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 **posterior**, please cite it as follows:\n\n* Bürkner P. C., Gabry J., Kay M., \u0026 Vehtari A. (2020). “posterior: Tools for\nWorking with Posterior Distributions.” R package version XXX, \u003cURL:\nhttps://mc-stan.org/posterior/\u003e.\n  \nWhen using the MCMC convergence diagnostics `rhat`, `ess_bulk`, `ess_tail`,\n`ess_median`, `ess_quantile`, `mcse_median`, or `mcse_quantile`\nplease also cite\n\n* Vehtari A., Gelman A., Simpson D., Carpenter B., \u0026 Bürkner P. C. (2021).\nRank-normalization, folding, and localization: An improved Rhat for assessing\nconvergence of MCMC (with discussion). *Bayesian Analysis*. 16(2), 667–718.\ndoi.org/10.1214/20-BA1221\n\nWhen using the MCMC convergence diagnostic `rhat_nested`\nplease also cite\n\n* Margossian, C. C., Hoffman, M. D., Sountsov, P., Riou-Durand, L.,\n  Vehtari, A., and Gelman, A. (2024).\n  Nested $\\widehat{R}$: Assessing the convergence of Markov chain\n  Monte Carlo when running many short chains. *Bayesian Analysis*,\n  doi:10.1214/24-BA1453. \n\nWhen using the MCMC convergence diagnostic `rstar`\nplease also cite\n\n* Lambert, B. and Vehtari, A. (2022). $R^*$: A robust MCMC convergence\n  diagnostic with uncertainty using decision tree classifiers.\n  *Bayesian Analysis*, 17(2):353-379.\n  doi:10.1214/20-BA1252\n\nWhen using the Pareto-k diagnostics `pareto_khat`, `pareto_min_ss`,\n`pareto_convergence_rate`, `khat_threshold` or `pareto_diags`, or\nPareto smoothing `pareto_smooth` please also cite\n\n* Vehtari, A., Simpson, D., Gelman, A., Yao, Y., and Gabry, J. (2024).\nPareto smoothed importance sampling.\n*Journal of Machine Learning Research*, 25(72):1-58.\n\nThe same information can be obtained by running `citation(\"posterior\")`.\n\n### References\n\nGelman A., Carlin J. B., Stern H. S., David B. Dunson D. B., Aki Vehtari A.,\n\u0026 Rubin D. B. (2013). *Bayesian Data Analysis, Third Edition*. Chapman and\nHall/CRC.\n\nLambert, B. and Vehtari, A. (2022). $R^*$: A robust MCMC convergence\ndiagnostic with uncertainty using decision tree classifiers.\n*Bayesian Analysis*, 17(2):353-379.\ndoi:10.1214/20-BA1252\n\nMargossian, C. C., Hoffman, M. D., Sountsov, P., Riou-Durand, L.,\nVehtari, A., and Gelman, A. (2024).\nNested $\\widehat{R}$: Assessing the convergence of Markov chain\nMonte Carlo when running many short chains. *Bayesian Analysis*,\ndoi:10.1214/24-BA1453.\n  \nVehtari A., Gelman A., Simpson D., Carpenter B., \u0026 Bürkner P. C. (2021).\nRank-normalization, folding, and localization: An improved Rhat for assessing\nconvergence of MCMC (with discussion). *Bayesian Analysis*. 16(2), 667–718.\ndoi.org/10.1214/20-BA1221\n\nVehtari, A., Simpson, D., Gelman, A., Yao, Y., and Gabry, J. (2024).\nPareto smoothed importance sampling.\n*Journal of Machine Learning Research*, 25(72):1-58.\n\n### Licensing\n\nThe **posterior** package is licensed under the following licenses:\n\n- Code: BSD 3-clause (https://opensource.org/license/bsd-3-clause)\n- Documentation: CC-BY 4.0 (https://creativecommons.org/licenses/by/4.0/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstan-dev%2Fposterior","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstan-dev%2Fposterior","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstan-dev%2Fposterior/lists"}