### Run Example Model with stan_glmer Source: https://mc-stan.org/rstanarm/reference/example_model.html This snippet demonstrates how to run a small example model using `stan_glmer`. It includes conditional execution for Windows i386 architecture and sets specific arguments (`chains`, `cores`, `iter`, `refresh`) to minimize example size. In practice, these arguments should be adjusted for convergence and performance. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { example_model <- stan_glmer(cbind(incidence, size - incidence) ~ size + period + (1|herd), data = lme4::cbpp, family = binomial, QR = TRUE, # this next line is only to keep the example small in size! chains = 2, cores = 1, seed = 12345, iter = 1000, refresh = 0) example_model } ``` -------------------------------- ### Install rstanarm from GitHub Source: https://mc-stan.org/rstanarm/index.html Install the development version of the rstanarm package from GitHub. Ensure rstan is installed first. ```r remotes::install_github("stan-dev/rstanarm", build_vignettes = FALSE) ``` -------------------------------- ### Install rstanarm from GitHub with Parallelization Source: https://mc-stan.org/rstanarm/index.html Installs the rstanarm package from GitHub, allowing for parallel installation using multiple cores. Adjust the '-j2' flag based on your system's capabilities to avoid memory issues. ```R Sys.setenv(MAKEFLAGS = "-j2") Sys.setenv("R_REMOTES_NO_ERRORS_FROM_WARNINGS" = "true") remotes::install_github("stan-dev/rstanarm", INSTALL_opts = "--no-multiarch", force = TRUE) ``` -------------------------------- ### Stan Sampling Output (Extended Warmup) Source: https://mc-stan.org/rstanarm/reference/priors.html This is an example of Stan's sampling output with a longer warmup period. It demonstrates the iteration progress and timing for both warmup and sampling phases. Note that this output does not contain the same warnings as the previous example, suggesting better chain mixing and ESS. ```text SAMPLING FOR MODEL 'continuous' NOW (CHAIN 1). Chain 1: Chain 1: Gradient evaluation took 2.5e-05 seconds Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0.25 seconds. Chain 1: Adjust your expectations accordingly! Chain 1: Chain 1: Chain 1: Iteration: 1 / 2000 [ 0%] (Warmup) Chain 1: Iteration: 200 / 2000 [ 10%] (Warmup) Chain 1: Iteration: 400 / 2000 [ 20%] (Warmup) Chain 1: Iteration: 600 / 2000 [ 30%] (Warmup) Chain 1: Iteration: 800 / 2000 [ 40%] (Warmup) Chain 1: Iteration: 1000 / 2000 [ 50%] (Warmup) Chain 1: Iteration: 1001 / 2000 [ 50%] (Sampling) Chain 1: Iteration: 1200 / 2000 [ 60%] (Sampling) Chain 1: Iteration: 1400 / 2000 [ 70%] (Sampling) Chain 1: Iteration: 1600 / 2000 [ 80%] (Sampling) Chain 1: Iteration: 1800 / 2000 [ 90%] (Sampling) Chain 1: Iteration: 2000 / 2000 [100%] (Sampling) Chain 1: Chain 1: Elapsed Time: 0.058 seconds (Warm-up) Chain 1: 0.055 seconds (Sampling) Chain 1: 0.113 seconds (Total) Chain 1: ``` -------------------------------- ### Example Usage: Posterior vs Prior Plot Source: https://mc-stan.org/rstanarm/reference/posterior_vs_prior.html This example demonstrates how to use the `posterior_vs_prior` function. It includes a platform-specific check to ensure the code runs on compatible systems. ```r if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { # Example usage would go here, but is omitted in the source } ``` -------------------------------- ### Example: Compute weighted predictions and intervals Source: https://mc-stan.org/rstanarm/reference/loo_predict.stanreg.html Demonstrates how to compute weighted linear predictions, prediction variances, and predictive intervals using pre-computed LOO weights (psis_object). This example includes a check for Windows i386 architecture to avoid potential issues. ```R __``` if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { # \dontrun{ if (!exists("example_model")) example(example_model) # optionally, log-weights can be pre-computed and reused psis_result <- loo::psis(log_ratios = -log_lik(example_model)) loo_probs <- loo_linpred(example_model, type = "mean", transform = TRUE, psis_object = psis_result) str(loo_probs) loo_pred_var <- loo_predict(example_model, type = "var", psis_object = psis_result) str(loo_pred_var) loo_pred_ints <- loo_predictive_interval(example_model, prob = 0.8, psis_object = psis_result) str(loo_pred_ints) # } } #> Warning: Some Pareto k diagnostic values are too high. See help('pareto-k-diagnostic') for details. #> Instead of posterior_linpred(..., transform=TRUE) please call posterior_epred(), which provides equivalent functionality. #> List of 2 #> $ value : num [1:56] 0.4294 0.1141 0.0679 0.0993 0.1687 ... #> $ pareto_k: num [1:56] 0.853 0.344 0.617 0.201 0.504 ... #> List of 2 #> $ value : num [1:56] 6.795 1.687 0.652 0.502 5.198 ... #> $ pareto_k: num [1:56] 1.067 0.344 0.661 0.131 0.575 ... #> List of 2 #> $ value : num [1:56, 1:2] 3 0 0 0 1 0 0 2 0 0 ... #> ..- attr(*, "dimnames")=List of 2 #> .. ..$ : NULL #> .. ..$ : chr [1:2] "10%" "90%" #> $ pareto_k: num [1:56] 0.791 0.344 0.617 0.131 0.425 ... ``` ``` -------------------------------- ### Example Plotting Survival Function Source: https://mc-stan.org/rstanarm/reference/plot.survfit.stanjm.html This example demonstrates how to plot the survival function using `plot.survfit.stanjm`. It includes a platform-specific condition to avoid issues on certain Windows architectures. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { # Example usage would go here, likely involving posterior_survfit and plot } ``` -------------------------------- ### Install rstanarm from CRAN Source: https://mc-stan.org/rstanarm/index.html Install the latest stable release of the rstanarm package from CRAN. ```r install.packages("rstanarm") ``` -------------------------------- ### K-fold Cross-Validation Example Source: https://mc-stan.org/rstanarm/reference/kfold.stanreg.html Demonstrates how to perform K-fold cross-validation on a fitted stanreg model. This example is conditional on the operating system and architecture to avoid potential issues on certain platforms. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { # Example usage of kfold (assuming 'fit' is a fitted stanreg object) # kfold_fit <- kfold(fit) } ``` -------------------------------- ### Install Development Version of rstanarm with Survival Analysis Source: https://mc-stan.org/rstanarm/index.html Installs a binary development version of rstanarm that includes survival analysis functionality. This version is from a specific repository and is static, meaning it won't auto-update. ```R install.packages("rstanarm", repos = c('https://stan-dev.r-universe.dev', getOption("repos"))) ``` -------------------------------- ### Example: Posterior Linear Predictor and Probabilities Source: https://mc-stan.org/rstanarm/reference/posterior_linpred.stanreg.html Demonstrates how to obtain the linear predictor on the log-odds scale and the corresponding probabilities using `posterior_linpred` and `posterior_epred`. It also shows how to exclude group-level parameters. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { if (!exists("example_model")) example(example_model) print(family(example_model)) # linear predictor on log-odds scale linpred <- posterior_linpred(example_model) colMeans(linpred) # probabilities # same as posterior_linpred(example_model, transform = TRUE) probs <- posterior_epred(example_model) colMeans(probs) # not conditioning on any group-level parameters probs2 <- posterior_epred(example_model, re.form = NA) apply(probs2, 2, median) } ``` -------------------------------- ### Access rstanarm Datasets Help Source: https://mc-stan.org/rstanarm/articles/jm.html Opens the help documentation for the `datasets` function within the `rstanarm` package. This is useful for understanding the structure and content of the example datasets. ```R help("datasets", package = "rstanarm") ``` -------------------------------- ### Example Usage of plot.predict.stanjm Source: https://mc-stan.org/rstanarm/reference/plot.predict.stanjm.html Demonstrates a conditional example usage of the plot function for predict.stanjm objects, likely to avoid issues on specific Windows configurations. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { # Example code would go here, but is not provided in the source. } ``` -------------------------------- ### Prior Summary Output Source: https://mc-stan.org/rstanarm/articles/priors.html Example output from prior_summary, detailing the priors for the intercept, coefficients, and auxiliary parameters after custom specification. ```text Priors for model 'test_no_autoscale' ------ Intercept (after predictors centered) ~ student_t(df = 4, location = 0, scale = 10) Coefficients ~ normal(location = [0,0], scale = [5,5]) Auxiliary (sigma) ~ half-cauchy(location = 0, scale = 3) ------ See help('prior_summary.stanreg') for more details ``` -------------------------------- ### Example usage of summary for stanreg Source: https://mc-stan.org/rstanarm/reference/summary.stanreg.html Demonstrates how to use the summary function on a fitted stanreg model, specifying probability quantiles. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { if (!exists("example_model")) example("example_model") summary(example_model, probs = c(0.1, 0.9)) } ``` -------------------------------- ### Example: Computing and Visualizing Predictive Errors Source: https://mc-stan.org/rstanarm/reference/predictive_error.stanreg.html This example demonstrates how to compute predictive errors for a stanreg model and visualize the distribution of these errors using a histogram. It includes platform-specific checks. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { if (!exists("example_model")) example(example_model) err1 <- predictive_error(example_model, draws = 50) hist(err1) } ``` -------------------------------- ### Run All rstanarm Tests Locally Source: https://mc-stan.org/rstanarm/dev-notes/testing.html This script demonstrates how to run all rstanarm tests locally, excluding vignettes. It includes loading necessary libraries and setting up a prerequisite example model for testing. ```R ### script to run all rstanarm tests locally library(rstanarm) # library(rstantools) # library(bayesplot) remove(list=ls()) ### run prerequisite functions # example_model <- stan_glmer(cbind(incidence, size - incidence) ~ size + period + (1|herd), data = lme4::cbpp, family = binomial, # this next line is only to keep the example small in size! chains = 2, cores = 1, seed = 12345, iter = 500) # last_dimnames <- function(x) { ndim <- length(dim(x)) dimnames(x)[[ndim]] } ### run tests devtools::test() ``` -------------------------------- ### Fitting a Univariate Joint Model with stan_jm Source: https://mc-stan.org/rstanarm/reference/plot.predict.stanjm.html This example demonstrates how to fit a univariate joint model using stan_jm. It specifies formulas for both the longitudinal and event processes, along with the time variable. Note that parameters like `chains`, `iter`, and `refresh` are set to small values for a quick example. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") example_jm <- stan_jm(formulaLong = logBili ~ year + (1 | id), dataLong = pbcLong[1:101,], formulaEvent = survival::Surv(futimeYears, death) ~ sex + trt, dataEvent = pbcSurv[1:15,], time_var = "year", # this next line is only to keep the example small in size! chains = 1, seed = 12345, iter = 100, refresh = 0) ``` -------------------------------- ### Fit and Visualize GAMM with stan_gamm4 Source: https://mc-stan.org/rstanarm/reference/stan_gamm4.html This example demonstrates fitting a generalized additive mixed model with random effects using stan_gamm4 and visualizing the nonlinear smooth terms. It includes a platform-specific check to avoid running on certain Windows configurations. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { # from example(gamm4, package = "gamm4"), prefixing gamm4() call with stan_ # \donttest{ dat <- mgcv::gamSim(1, n = 400, scale = 2) ## simulate 4 term additive truth ## Now add 20 level random effect `fac'... dat$fac <- fac <- as.factor(sample(1:20, 400, replace = TRUE)) dat$y <- dat$y + model.matrix(~ fac - 1) %*% rnorm(20) * .5 br <- stan_gamm4(y ~ s(x0) + x1 + s(x2), data = dat, random = ~ (1 | fac), chains = 1, iter = 500) # for example speed print(br) plot_nonlinear(br) plot_nonlinear(br, smooths = "s(x0)", alpha = 2/3) # } } ``` -------------------------------- ### Compute Posterior Intervals for a Stanreg Model Source: https://mc-stan.org/rstanarm/reference/posterior_interval.stanreg.html Demonstrates how to compute posterior intervals for a fitted stanreg model. This example shows the default usage of the posterior_interval function. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { if (!exists("example_model")) example(example_model) posterior_interval(example_model) posterior_interval(example_model, regex_pars = "herd") posterior_interval(example_model, pars = "period2", prob = 0.5) } #> 25% 75% #> period2 -1.190268 -0.7887574 ``` -------------------------------- ### Stan Clogit Sampling Output Source: https://mc-stan.org/rstanarm/reference/stan_clogit.html Example of the sampling output from a Stan Clogit model. It shows the progress of sampling chains, gradient evaluation times, and elapsed time for warmup and sampling phases. ```text SAMPLING FOR MODEL 'bernoulli' NOW (CHAIN 1). Chain 1: Chain 1: Gradient evaluation took 5.8e-05 seconds Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0.58 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.233 seconds (Warm-up) Chain 1: 0.083 seconds (Sampling) Chain 1: 0.316 seconds (Total) Chain 1: SAMPLING FOR MODEL 'bernoulli' NOW (CHAIN 2). Chain 2: Chain 2: Gradient evaluation took 4.1e-05 seconds Chain 2: 1000 transitions using 10 leapfrog steps per transition would take 0.41 seconds. Chain 2: Adjust your expectations accordingly! Chain 2: Chain 2: Chain 2: Iteration: 1 / 500 [ 0%] (Warmup) Chain 2: Iteration: 50 / 500 [ 10%] (Warmup) Chain 2: Iteration: 100 / 500 [ 20%] (Warmup) Chain 2: Iteration: 150 / 500 [ 30%] (Warmup) Chain 2: Iteration: 200 / 500 [ 40%] (Warmup) Chain 2: Iteration: 250 / 500 [ 50%] (Warmup) Chain 2: Iteration: 251 / 500 [ 50%] (Sampling) Chain 2: Iteration: 300 / 500 [ 60%] (Sampling) Chain 2: Iteration: 350 / 500 [ 70%] (Sampling) Chain 2: Iteration: 400 / 500 [ 80%] (Sampling) Chain 2: Iteration: 450 / 500 [ 90%] (Sampling) Chain 2: Iteration: 500 / 500 [100%] (Sampling) Chain 2: Chain 2: Elapsed Time: 0.306 seconds (Warm-up) Chain 2: 0.12 seconds (Sampling) Chain 2: 0.426 seconds (Total) Chain 2: [1] TRUE ``` -------------------------------- ### Launch ShinyStan Source: https://mc-stan.org/rstanarm/reference/index.html Launches the ShinyStan GUI for visualizing rstanarm models. ```APIDOC `launch_shinystan(__)` Using the ShinyStan GUI with rstanarm models ``` -------------------------------- ### Example of using pp_check with stan_glmer Source: https://mc-stan.org/rstanarm/reference/pp_check.stanreg.html This example demonstrates how to use the pp_check function with a stan_glmer model. It fits a model and then generates a posterior predictive check plot. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch != "i386") { fit <- stan_glmer( mpg ~ wt + am + (1|cyl), data = mtcars, iter = 400, # iter and chains small just to keep example quick chains = 2, refresh = 0 ) pp_check(fit, plotfun = "dens_overlay") pp_check(fit, plotfun = "hist", nreps = 50) pp_check(fit, plotfun = "stat", stat = "mean") pp_check(fit, plotfun = "stat_grouped", stat = "mean", group = "am") pp_check(fit, plotfun = "stat_2d", stat = c("mean", "sd")) pp_check(fit, plotfun = "stat_3d", stat = c("mean", "sd", "median")) pp_check(fit, plotfun = "intervals", prob = 0.9) pp_check(fit, plotfun = "loo_pit") pp_check(fit, plotfun = "loo_pit_overlay") pp_check(fit, plotfun = "loo_overlay") pp_check(fit, plotfun = "ppp_overlay") pp_check(fit, plotfun = "overlay") pp_check(fit, plotfun = "bars") pp_check(fit, plotfun = "scatter_avg") pp_check(fit, plotfun = "scatter_mean") pp_check(fit, plotfun = "scatter_median") pp_check(fit, plotfun = "scatter_rms") pp_check(fit, plotfun = "ecdf_overlay") pp_check(fit, plotfun = "cdfs") pp_check(fit, plotfun = "cdfs_overlay") pp_check(fit, plotfun = "qq_overlay") pp_check(fit, plotfun = "qq_plot") pp_check(fit, plotfun = "rootogram") pp_check(fit, plotfun = "error_hist") pp_check(fit, plotfun = "error_scatter_avg") pp_check(fit, plotfun = "error_scatter_avg_vs_group") pp_check(fit, plotfun = "error_scatter_avg_vs_x") pp_check(fit, plotfun = "error_density") pp_check(fit, plotfun = "error_density_vs_group") pp_check(fit, plotfun = "error_density_vs_x") pp_check(fit, plotfun = "error_bars") pp_check(fit, plotfun = "error_bars_vs_group") pp_check(fit, plotfun = "error_bars_vs_x") pp_check(fit, plotfun = "bars_cumulative") pp_check(fit, plotfun = "bars_grouped") pp_check(fit, plotfun = "bars_grouped_cumulative") pp_check(fit, plotfun = "bars_cumulative_vs_group") pp_check(fit, plotfun = "bars_cumulative_vs_x") pp_check(fit, plotfun = "bars_grouped_vs_group") pp_check(fit, plotfun = "bars_grouped_vs_x") pp_check(fit, plotfun = "bars_grouped_cumulative_vs_group") pp_check(fit, plotfun = "bars_grouped_cumulative_vs_x") pp_check(fit, plotfun = "ppc_dens_overlay") pp_check(fit, plotfun = "ppc_hist") pp_check(fit, plotfun = "ppc_stat", stat = "mean") pp_check(fit, plotfun = "ppc_stat_grouped", stat = "mean", group = "am") pp_check(fit, plotfun = "ppc_stat_2d", stat = c("mean", "sd")) pp_check(fit, plotfun = "ppc_stat_3d", stat = c("mean", "sd", "median")) pp_check(fit, plotfun = "ppc_intervals", prob = 0.9) pp_check(fit, plotfun = "ppc_loo_pit") pp_check(fit, plotfun = "ppc_loo_pit_overlay") pp_check(fit, plotfun = "ppc_loo_overlay") pp_check(fit, plotfun = "ppc_ppp_overlay") pp_check(fit, plotfun = "ppc_overlay") pp_check(fit, plotfun = "ppc_bars") pp_check(fit, plotfun = "ppc_scatter_avg") pp_check(fit, plotfun = "ppc_scatter_mean") pp_check(fit, plotfun = "ppc_scatter_median") pp_check(fit, plotfun = "ppc_scatter_rms") pp_check(fit, plotfun = "ppc_ecdf_overlay") pp_check(fit, plotfun = "ppc_cdfs") pp_check(fit, plotfun = "ppc_cdfs_overlay") pp_check(fit, plotfun = "ppc_qq_overlay") pp_check(fit, plotfun = "ppc_qq_plot") pp_check(fit, plotfun = "ppc_rootogram") pp_check(fit, plotfun = "ppc_error_hist") pp_check(fit, plotfun = "ppc_error_scatter_avg") pp_check(fit, plotfun = "ppc_error_scatter_avg_vs_group") pp_check(fit, plotfun = "ppc_error_scatter_avg_vs_x") pp_check(fit, plotfun = "ppc_error_density") pp_check(fit, plotfun = "ppc_error_density_vs_group") pp_check(fit, plotfun = "ppc_error_density_vs_x") pp_check(fit, plotfun = "ppc_error_bars") pp_check(fit, plotfun = "ppc_error_bars_vs_group") pp_check(fit, plotfun = "ppc_error_bars_vs_x") pp_check(fit, plotfun = "ppc_bars_cumulative") pp_check(fit, plotfun = "ppc_bars_grouped") pp_check(fit, plotfun = "ppc_bars_grouped_cumulative") pp_check(fit, plotfun = "ppc_bars_cumulative_vs_group") pp_check(fit, plotfun = "ppc_bars_cumulative_vs_x") pp_check(fit, plotfun = "ppc_bars_grouped_vs_group") pp_check(fit, plotfun = "ppc_bars_grouped_vs_x") pp_check(fit, plotfun = "ppc_bars_grouped_cumulative_vs_group") pp_check(fit, plotfun = "ppc_bars_grouped_cumulative_vs_x") } ``` -------------------------------- ### Specify Cores for K-fold (Method 1) Source: https://mc-stan.org/rstanarm/reference/kfold.stanreg.html Demonstrates spreading K models over N_CORES using the 'cores' argument directly in the kfold function. ```R # spread the K models over N_CORES cores (method 1) kfold(fit, K, cores = N_CORES) ``` -------------------------------- ### Create shinystan object then launch app Source: https://mc-stan.org/rstanarm/reference/launch_shinystan.stanreg.html First creates a shinystan object from an rstanarm model, then launches the ShinyStan app using this object. ```R sso <- shinystan::as.shinystan(example_model) if (interactive()) launch_shinystan(sso) ``` -------------------------------- ### Specify Cores for K-fold (Method 2) Source: https://mc-stan.org/rstanarm/reference/kfold.stanreg.html Shows how to set the global 'mc.cores' option to spread K models over N_CORES. This method is useful when multiple functions might benefit from the same core setting. ```R # spread the K models over N_CORES cores (method 2) options(mc.cores = N_CORES) kfold(fit, K) ``` -------------------------------- ### Prepare Data for Visualization Source: https://mc-stan.org/rstanarm/articles/mrp.html This code prepares the 'sample', 'true_popn', and 'poststrat' data frames by ensuring the 'state' variable is a factor with consistent levels. This is a necessary step for accurate plotting and comparison between datasets. ```R sample$state <- factor(sample$state, levels=1:50) sample$state <- with(sample, factor(state, levels=order(table(state)))) true_popn$state <- factor(true_popn$state,levels = levels(sample$state)) poststrat$state <- factor(poststrat$state,levels = levels(sample$state)) ``` -------------------------------- ### Fit Proportional Odds Logistic Regression Source: https://mc-stan.org/rstanarm/reference/stan_polr.html Fits a proportional odds logistic regression model using the probit link function. Includes example prior specification and plotting of results. This example is conditional on the operating system and architecture to avoid issues on Windows i386. ```R if (.Platform$OS.type != "windows" || .Platform$r_arch !="i386") { fit <- stan_polr(tobgp ~ agegp, data = esoph, method = "probit", prior = R2(0.2, "mean"), init_r = 0.1, seed = 12345, algorithm = "fullrank") # for speed only print(fit) plot(fit) } #> Chain 1: ------------------------------------------------------------ #> Chain 1: EXPERIMENTAL ALGORITHM: #> Chain 1: This procedure has not been thoroughly tested and may be unstable #> Chain 1: or buggy. The interface is subject to change. #> Chain 1: ------------------------------------------------------------ #> Chain 1: #> Chain 1: #> Chain 1: #> Chain 1: Gradient evaluation took 5.5e-05 seconds #> Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0.55 seconds. #> Chain 1: Adjust your expectations accordingly! #> Chain 1: #> Chain 1: #> Chain 1: Begin eta adaptation. #> Chain 1: Iteration: 1 / 250 [ 0%] (Adaptation) #> Chain 1: Iteration: 50 / 250 [ 20%] (Adaptation) #> Chain 1: Iteration: 100 / 250 [ 40%] (Adaptation) #> Chain 1: Iteration: 150 / 250 [ 60%] (Adaptation) #> Chain 1: Iteration: 200 / 250 [ 80%] (Adaptation) #> Chain 1: Success! Found best value [eta = 1] earlier than expected. #> Chain 1: #> Chain 1: Begin stochastic gradient ascent. #> Chain 1: iter ELBO delta_ELBO_mean delta_ELBO_med notes #> Chain 1: 100 -135.991 1.000 1.000 #> Chain 1: 200 -131.110 0.519 1.000 #> Chain 1: 300 -128.295 0.353 0.037 #> Chain 1: 400 -127.636 0.266 0.037 #> Chain 1: 500 -127.828 0.213 0.022 #> Chain 1: 600 -127.903 0.178 0.022 #> Chain 1: 700 -127.740 0.153 0.005 MEDIAN ELBO CONVERGED #> Chain 1: #> Chain 1: Drawing a sample of size 1000 from the approximate posterior... #> Chain 1: COMPLETED. #> stan_polr #> family: ordered [probit] #> formula: tobgp ~ agegp #> observations: 88 #> ------ #> Median MAD_SD #> agegp.L -0.1 0.3 #> agegp.Q -0.2 0.2 #> agegp.C 0.0 0.3 #> agegp^4 0.0 0.2 #> agegp^5 0.0 0.2 #> #> Cutpoints: #> Median MAD_SD #> 0-9g/day|10-19 -0.6 0.1 #> 10-19|20-29 0.1 0.1 #> 20-29|30+ 0.8 0.2 #> #> ------ #> * For help interpreting the printed output see ?print.stanreg #> * For info on the priors used see ?prior_summary.stanreg ``` -------------------------------- ### Get Fitted Values Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Extracts fitted values from a stanreg object. ```R fitted(object, ...) ``` -------------------------------- ### Launch ShinyStan for Model Visualization Source: https://mc-stan.org/rstanarm/articles/rstanarm.html Opens an interactive web browser for visualizing posterior distributions and diagnosing Markov chain problems. Set ppd = TRUE to include posterior predictive distributions. ```r launch_shinystan(womensrole_bglm_1, ppd = FALSE) ``` -------------------------------- ### Get Sigma Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Extracts the estimated scale parameter (sigma) from a stanreg object. ```R sigma(object, ...) ``` -------------------------------- ### Stan Sampling Output (Multiple Chains) Source: https://mc-stan.org/rstanarm/reference/priors.html This example shows Stan's sampling output for multiple chains (Chain 2 and Chain 3). It details the progress, timing, and adaptation parameters for each chain, illustrating the parallel processing of MCMC chains. ```text SAMPLING FOR MODEL 'continuous' NOW (CHAIN 2). Chain 2: Chain 2: Gradient evaluation took 1.4e-05 seconds Chain 2: 1000 transitions using 10 leapfrog steps per transition would take 0.14 seconds. Chain 2: Adjust your expectations accordingly! Chain 2: Chain 2: Chain 2: Iteration: 1 / 2000 [ 0%] (Warmup) Chain 2: Iteration: 200 / 2000 [ 10%] (Warmup) Chain 2: Iteration: 400 / 2000 [ 20%] (Warmup) Chain 2: Iteration: 600 / 2000 [ 30%] (Warmup) Chain 2: Iteration: 800 / 2000 [ 40%] (Warmup) Chain 2: Iteration: 1000 / 2000 [ 50%] (Warmup) Chain 2: Iteration: 1001 / 2000 [ 50%] (Sampling) Chain 2: Iteration: 1200 / 2000 [ 60%] (Sampling) Chain 2: Iteration: 1400 / 2000 [ 70%] (Sampling) Chain 2: Iteration: 1600 / 2000 [ 80%] (Sampling) Chain 2: Iteration: 1800 / 2000 [ 90%] (Sampling) Chain 2: Iteration: 2000 / 2000 [100%] (Sampling) Chain 2: Chain 2: Elapsed Time: 0.06 seconds (Warm-up) Chain 2: 0.06 seconds (Sampling) Chain 2: 0.12 seconds (Total) Chain 2: SAMPLING FOR MODEL 'continuous' NOW (CHAIN 3). Chain 3: Chain 3: Gradient evaluation took 1.3e-05 seconds Chain 3: 1000 transitions using 10 leapfrog steps per transition would take 0.13 seconds. Chain 3: Adjust your expectations accordingly! Chain 3: Chain 3: Chain 3: Iteration: 1 / 2000 [ 0%] (Warmup) Chain 3: Iteration: 200 / 2000 [ 10%] (Warmup) Chain 3: Iteration: 400 / 2000 [ 20%] (Warmup) ``` -------------------------------- ### Get Random Effects Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Extracts random effects from a fitted stanmvreg object. ```R ranef(object, ...) ``` -------------------------------- ### Stan Sampling Output with Warnings Source: https://mc-stan.org/rstanarm/reference/priors.html This is an example of Stan's sampling output. Pay attention to warnings regarding R-hat values and effective sample size (ESS), which indicate potential issues with chain convergence and reliability of posterior estimates. The output shows adaptation stages and elapsed times for warmup and sampling. ```text SAMPLING FOR MODEL 'continuous' NOW (CHAIN 1). Chain 1: Chain 1: Gradient evaluation took 2.6e-05 seconds Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0.26 seconds. Chain 1: Adjust your expectations accordingly! Chain 1: Chain 1: Chain 1: WARNING: There aren't enough warmup iterations to fit the Chain 1: three stages of adaptation as currently configured. Chain 1: Reducing each adaptation stage to 15%/75%/10% of Chain 1: the given number of warmup iterations: Chain 1: init_buffer = 18 Chain 1: adapt_window = 95 Chain 1: term_buffer = 12 Chain 1: Chain 1: Iteration: 1 / 250 [ 0%] (Warmup) Chain 1: Iteration: 25 / 250 [ 10%] (Warmup) Chain 1: Iteration: 50 / 250 [ 20%] (Warmup) Chain 1: Iteration: 75 / 250 [ 30%] (Warmup) Chain 1: Iteration: 100 / 250 [ 40%] (Warmup) Chain 1: Iteration: 125 / 250 [ 50%] (Warmup) Chain 1: Iteration: 126 / 250 [ 50%] (Sampling) Chain 1: Iteration: 150 / 250 [ 60%] (Sampling) Chain 1: Iteration: 175 / 250 [ 70%] (Sampling) Chain 1: Iteration: 200 / 250 [ 80%] (Sampling) Chain 1: Iteration: 225 / 250 [ 90%] (Sampling) Chain 1: Iteration: 250 / 250 [100%] (Sampling) Chain 1: Chain 1: Elapsed Time: 0.024 seconds (Warm-up) Chain 1: 0.025 seconds (Sampling) Chain 1: 0.049 seconds (Total) Chain 1: Warning: The largest R-hat is 1.14, 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 ``` -------------------------------- ### Fit Joint Longitudinal and Time-to-Event Model Source: https://mc-stan.org/rstanarm/reference/example_jm.html Demonstrates fitting a joint model for longitudinal and time-to-event data. The `chains` and `iter` arguments are set low for a small example; increase these for actual use. Consider setting `cores` on multicore systems. The example is skipped on Windows i386 due to potential compatibility issues. ```R # set.seed(123) if (.Platform$OS.type != "windows" || .Platform$r_arch !="i386") example_jm <- stan_jm(formulaLong = logBili ~ year + (1 | id), dataLong = pbcLong[1:101,], formulaEvent = survival::Surv(futimeYears, death) ~ sex + trt, dataEvent = pbcSurv[1:15,], time_var = "year", # this next line is only to keep the example small in size! chains = 1, seed = 12345, iter = 100, refresh = 0) ``` -------------------------------- ### Get Number of Samples Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Returns the number of posterior draws obtained for a stanreg object. ```R nsamples(object, ...) ``` -------------------------------- ### Get Fixed Effects Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Extracts fixed effect parameters from a fitted stanmvreg object. ```R fixef(object, ...) ``` -------------------------------- ### Compare Prior Distributions Source: https://mc-stan.org/rstanarm/reference/priors.html Visualizes and compares the probability density functions of normal, student_t, cauchy, laplace, and product_normal distributions. Useful for selecting appropriate priors based on desired tail behavior. ```R compare_priors <- function(scale = 1, df_t = 2, xlim = c(-10, 10)) { dt_loc_scale <- function(x, df, location, scale) { 1/scale * dt((x - location)/scale, df) } dlaplace <- function(x, location, scale) { 0.5 / scale * exp(-abs(x - location) / scale) } dproduct_normal <- function(x, scale) { besselK(abs(x) / scale ^ 2, nu = 0) / (scale ^ 2 * pi) } stat_dist <- function(dist, ...) { ggplot2::stat_function(ggplot2::aes_(color = dist), ...) } ggplot2::ggplot(data.frame(x = xlim), ggplot2::aes(x)) + stat_dist("normal", size = .75, fun = dnorm, args = list(mean = 0, sd = scale)) + stat_dist("student_t", size = .75, fun = dt_loc_scale, args = list(df = df_t, location = 0, scale = scale)) + stat_dist("cauchy", size = .75, linetype = 2, fun = dcauchy, args = list(location = 0, scale = scale)) + stat_dist("laplace", size = .75, linetype = 2, fun = dlaplace, args = list(location = 0, scale = scale)) + stat_dist("product_normal", size = .75, linetype = 2, fun = dproduct_normal, args = list(scale = 1)) } # Cauchy has fattest tails, followed by student_t, laplace, and normal compare_priors() ``` ```R # The student_t with df = 1 is the same as the cauchy compare_priors(df_t = 1) ``` ```R # Even a scale of 5 is somewhat large. It gives plausibility to rather # extreme values compare_priors(scale = 5, xlim = c(-20,20)) ``` -------------------------------- ### Build RStan Package Documentation with Pkgdown Source: https://mc-stan.org/rstanarm/dev-notes/meta.html Renders HTML documentation files for the RStan package using pkgdown. This command should be run from the RStan package directory after updating the master and gh-pages branches. ```r pkgdown::build_site(pkg = ".", path = "../..") ``` -------------------------------- ### Get Coefficients Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Extracts coefficients (medians of posterior draws) from a fitted stanreg object. ```R coef(object, ...) ``` -------------------------------- ### Get Number of Groups Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Retrieves the number of groups for random effects in a fitted stanreg object. ```R ngrps(object, ...) ``` -------------------------------- ### Get Number of Observations Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Retrieves the number of observations from a fitted stanreg or stanmvreg model object. ```R nobs(object, ...) ``` ```R nobs(object, ...) ``` -------------------------------- ### Get Variance Components Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Extracts variance components from a stanreg object, similar to VarCorr for mixed models. ```R VarCorr(x, sigma = 1, ...) ``` -------------------------------- ### Get Variance-Covariance Matrix Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Returns the covariance matrix (or correlation matrix if TRUE) for parameters in a stanreg object. ```R vcov(object, correlation = FALSE, ...) ``` -------------------------------- ### Sequential K-fold with Parallel Chains Source: https://mc-stan.org/rstanarm/reference/kfold.stanreg.html Explains how to fit K models sequentially while utilizing N_CORES for the Markov chains within each model fit. This is achieved by setting 'cores = 1' for the kfold function and configuring 'mc.cores' globally. ```R # fit K models sequentially using N_CORES cores for the Markov chains each time options(mc.cores = N_CORES) kfold(fit, K, cores = 1) ``` -------------------------------- ### Get Residuals Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Extracts residuals from a stanreg object. Residuals are always of type "response". ```R residuals(object, ...) ``` -------------------------------- ### Print Method Source: https://mc-stan.org/rstanarm/reference/index.html Prints summary information for rstanarm objects. ```APIDOC `print(__)``print(__)` Print method for stanreg objects ``` -------------------------------- ### Computing model weights with precomputed LOO objects Source: https://mc-stan.org/rstanarm/reference/loo.stanreg.html Compute model weights using a list of precomputed LOO objects. The names in the list are optional but affect printing. ```R loo_list <- list(A = loo1, B = loo2, C = loo3) # names optional (affects printing) loo_model_weights(loo_list) ``` -------------------------------- ### Get Confidence Intervals Source: https://mc-stan.org/rstanarm/reference/stanreg-methods.html Computes confidence intervals for parameters in a stanreg object. For sampling-based fits, posterior_interval should be used instead. ```R confint(object, parm, level = 0.95, ...) ``` -------------------------------- ### Launch ShinyStan and save object Source: https://mc-stan.org/rstanarm/reference/launch_shinystan.stanreg.html Launches the ShinyStan app and saves the resulting shinystan object to a variable for later use. ```R if (interactive()) sso <- launch_shinystan(example_model) ``` -------------------------------- ### Build Other R Package Documentation with Pkgdown Source: https://mc-stan.org/rstanarm/dev-notes/meta.html Renders HTML documentation files for other R packages using pkgdown. Ensure vignette names in the \vignettes folder match those in \_pkgdown.yml. This command should be run from the package directory. ```r pkgdown::build_site(pkg = ".", path = ".") ``` -------------------------------- ### Load and Display Baseball Data Source: https://mc-stan.org/rstanarm/articles/pooling.html Loads the bball1970 dataset from rstanarm and prints it to the console. Ensure the rstanarm package is installed and loaded. ```r library(rstanarm) data(bball1970) bball <- bball1970 print(bball) ``` -------------------------------- ### Available Algorithms Source: https://mc-stan.org/rstanarm/reference/index.html Lists the estimation algorithms available for rstanarm models. ```APIDOC ## Available Algorithms `available-algorithms` Estimation algorithms available for rstanarm models ``` -------------------------------- ### Get formula for stanmvreg objects Source: https://mc-stan.org/rstanarm/reference/stanmvreg-methods.html Retrieves the formula from a stanmvreg object. Allows specifying fixed-only, random-only, or a specific submodel ('m'). ```R formula(x, fixed.only = FALSE, random.only = FALSE, m = NULL, ...) ```