# Accessing the contents of a stanfit object

#### Stan Development Team

#### 2025-03-10

This vignette demonstrates how to access most of data stored in a stanfit object. A stanfit object (an object of class `"stanfit"`) contains the output derived from fitting a Stan model using Markov chain Monte Carlo or one of Stan’s variational approximations (meanfield or full-rank). Throughout the document we’ll use the stanfit object obtained from fitting the Eight Schools example model:

    library(rstan)
    fit <- stan_demo("eight_schools", refresh = 0)

    Warning: There were 2 divergent transitions after warmup. See
    https://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
    to find out why this is a problem and how to eliminate them.

    Warning: Examine the pairs() plot to diagnose sampling problems

    class(fit)

    [1] "stanfit"
    attr(,"package")
    [1] "rstan"

## Posterior draws

There are several functions that can be used to access the draws from the posterior distribution stored in a stanfit object. These are `extract`, `as.matrix`, `as.data.frame`, and `as.array`, each of which returns the draws in a different format.

#### extract()

The `extract` function (with its default arguments) returns a list with named components corresponding to the model parameters.

    list_of_draws <- extract(fit)
    print(names(list_of_draws))

    [1] "mu"    "tau"   "eta"   "theta" "lp__"

In this model the parameters `mu` and `tau` are scalars and `theta` is a vector with eight elements. This means that the draws for `mu` and `tau` will be vectors (with length equal to the number of post-warmup iterations times the number of chains) and the draws for `theta` will be a matrix, with each column corresponding to one of the eight components:

    head(list_of_draws$mu)

    [1]  1.488474 12.571451 13.223202 13.182046  9.952339  6.912193

    head(list_of_draws$tau)

    [1]  7.348914  2.445517 11.517335  6.213301  2.031371  6.779524

    head(list_of_draws$theta)

    iterations      [,1]      [,2]      [,3]      [,4]       [,5]       [,6]
          [1,]  1.421816  8.687649 -4.603498  3.790294  -7.045458  0.2615451
          [2,] 18.550676  7.680755  8.966955  9.016272  11.423769 11.2204210
          [3,] 19.469451 15.344126 -7.727168 12.178930 -10.599775 -0.3549827
          [4,] 17.924275 18.694583  5.284061  6.666718  15.316291  7.8929871
          [5,]  6.701938  9.075823  7.907170  9.715682   8.907089  8.4608342
          [6,] 18.766974  4.349427 17.361541 15.550801  10.938264  8.9511055

    iterations      [,7]      [,8]
          [1,]  5.431451  3.543596
          [2,] 10.538840 11.336251
          [3,] 22.247510 15.918756
          [4,] 12.085506  6.242551
          [5,] 11.771131 10.389010
          [6,]  1.082676 16.802566

#### as.matrix(), as.data.frame(), as.array()

The `as.matrix`, `as.data.frame`, and `as.array` functions can also be used to retrieve the posterior draws from a stanfit object:

    matrix_of_draws <- as.matrix(fit)
    print(colnames(matrix_of_draws))

     [1] "mu"       "tau"      "eta[1]"   "eta[2]"   "eta[3]"   "eta[4]"
     [7] "eta[5]"   "eta[6]"   "eta[7]"   "eta[8]"   "theta[1]" "theta[2]"
    [13] "theta[3]" "theta[4]" "theta[5]" "theta[6]" "theta[7]" "theta[8]"
    [19] "lp__"

    df_of_draws <- as.data.frame(fit)
    print(colnames(df_of_draws))

     [1] "mu"       "tau"      "eta[1]"   "eta[2]"   "eta[3]"   "eta[4]"
     [7] "eta[5]"   "eta[6]"   "eta[7]"   "eta[8]"   "theta[1]" "theta[2]"
    [13] "theta[3]" "theta[4]" "theta[5]" "theta[6]" "theta[7]" "theta[8]"
    [19] "lp__"

    array_of_draws <- as.array(fit)
    print(dimnames(array_of_draws))

    $iterations
    NULL

    $chains
    [1] "chain:1" "chain:2" "chain:3" "chain:4"

    $parameters
     [1] "mu"       "tau"      "eta[1]"   "eta[2]"   "eta[3]"   "eta[4]"
     [7] "eta[5]"   "eta[6]"   "eta[7]"   "eta[8]"   "theta[1]" "theta[2]"
    [13] "theta[3]" "theta[4]" "theta[5]" "theta[6]" "theta[7]" "theta[8]"
    [19] "lp__"

The `as.matrix` and `as.data.frame` methods essentially return the same thing except in matrix and data frame form, respectively. The `as.array` method returns the draws from each chain separately and so has an additional dimension:

    print(dim(matrix_of_draws))
    print(dim(df_of_draws))
    print(dim(array_of_draws))

    [1] 4000   19
    [1] 4000   19
    [1] 1000    4   19

By default all of the functions for retrieving the posterior draws return the draws for all parameters (and generated quantities). The optional argument `pars` (a character vector) can be used if only a subset of the parameters is desired, for example:

    mu_and_theta1 <- as.matrix(fit, pars = c("mu", "theta[1]"))
    head(mu_and_theta1)

              parameters
    iterations        mu  theta[1]
          [1,]  9.113228 16.140227
          [2,]  7.255361 13.368290
          [3,]  8.528363  6.428964
          [4,] 11.081210 10.227082
          [5,]  6.307817 17.404911
          [6,]  9.964439 10.520016

## Posterior summary statistics and convergence diagnostics

Summary statistics are obtained using the `summary` function. The object returned is a list with two components:

    fit_summary <- summary(fit)
    print(names(fit_summary))

    [1] "summary"   "c_summary"

In `fit_summary$summary` all chains are merged whereas `fit_summary$c_summary` contains summaries for each chain individually. Typically we want the summary for all chains merged, which is what we’ll focus on here.

The summary is a matrix with rows corresponding to parameters and columns to the various summary quantities. These include the posterior mean, the posterior standard deviation, and various quantiles computed from the draws. The `probs` argument can be used to specify which quantiles to compute and `pars` can be used to specify a subset of parameters to include in the summary.

For models fit using MCMC, also included in the summary are the Monte Carlo standard error (`se_mean`), the effective sample size (`n_eff`), and the R-hat statistic (`Rhat`).

    print(fit_summary$summary)

                      mean    se_mean        sd        2.5%         25%
    mu         8.007536523 0.11552570 4.9513594  -1.9222026   4.8085181
    tau        6.603336325 0.20329568 5.9753551   0.1728432   2.3550279
    eta[1]     0.405848953 0.01740855 0.9445708  -1.5378558  -0.2115446
    eta[2]    -0.005753395 0.01536444 0.8715120  -1.7185355  -0.5699245
    eta[3]    -0.193857013 0.01468770 0.9281523  -1.9635021  -0.7952254
    eta[4]    -0.029155838 0.01411412 0.8804588  -1.7737136  -0.6176649
    eta[5]    -0.375402748 0.01516514 0.8448021  -2.0341022  -0.9238896
    eta[6]    -0.241978864 0.01642085 0.8841485  -1.9634660  -0.8197734
    eta[7]     0.359738764 0.01419410 0.8817446  -1.4207733  -0.2133717
    eta[8]     0.042265806 0.01497848 0.9345390  -1.8312333  -0.5703946
    theta[1]  11.617935090 0.15769026 8.0765444  -1.7867502   6.2750730
    theta[2]   7.861712373 0.09983657 6.1704677  -4.3241709   3.9818037
    theta[3]   6.206286455 0.14492356 7.7547427 -11.6068964   2.2516888
    theta[4]   7.716195812 0.10641752 6.4435087  -5.8913169   3.8734140
    theta[5]   5.135076545 0.10994314 6.3509612  -8.5487429   1.3567338
    theta[6]   6.066552756 0.11290372 6.5880615  -8.2913121   2.2740856
    theta[7]  10.848994521 0.11477964 6.6068494  -0.6215770   6.3721026
    theta[8]   8.423405371 0.16037401 7.7122152  -6.9216603   3.9199716
    lp__     -39.511483098 0.08383706 2.7126153 -45.6854960 -41.0851014
                      50%         75%      97.5%     n_eff      Rhat
    mu         7.99938904  11.2302155  17.788888 1836.9262 1.0008051
    tau        5.32920107   9.1688847  20.906005  863.9153 1.0092509
    eta[1]     0.42352102   1.0301003   2.286020 2944.0421 1.0015993
    eta[2]    -0.01734074   0.5535907   1.747688 3217.4620 0.9995929
    eta[3]    -0.22615731   0.4379316   1.668864 3993.2935 0.9998402
    eta[4]    -0.02884515   0.5350051   1.766398 3891.4407 1.0001105
    eta[5]    -0.38248559   0.1727490   1.348492 3103.2517 1.0001840
    eta[6]    -0.25233752   0.3164041   1.546743 2899.0733 1.0004464
    eta[7]     0.37455001   0.9322649   2.112452 3858.9593 0.9992021
    eta[8]     0.03593027   0.6630956   1.892417 3892.7749 0.9999310
    theta[1]  10.58113818  15.7662776  30.691080 2623.2604 1.0027785
    theta[2]   7.86537082  11.7120898  20.491776 3819.9426 1.0007652
    theta[3]   6.73261820  10.9262648  20.222523 2863.2339 1.0005658
    theta[4]   7.78588984  11.7445980  20.171425 3666.2201 1.0008216
    theta[5]   5.67497248   9.4494177  16.407779 3336.8956 1.0012809
    theta[6]   6.44470369  10.3757100  18.241870 3404.8561 1.0017153
    theta[7]  10.25285845  14.6639662  25.201119 3313.2870 1.0007526
    theta[8]   8.20517778  12.7200294  25.290306 2312.5454 0.9996591
    lp__     -39.23347400 -37.6547307 -34.883334 1046.8978 1.0039047

If, for example, we wanted the only quantiles included to be 10% and 90%, and for only the parameters included to be `mu` and `tau`, we would specify that like this:

    mu_tau_summary <- summary(fit, pars = c("mu", "tau"), probs = c(0.1, 0.9))$summary
    print(mu_tau_summary)

            mean   se_mean       sd       10%      90%     n_eff     Rhat
    mu  8.007537 0.1155257 4.951359 1.7419720 14.30474 1836.9262 1.000805
    tau 6.603336 0.2032957 5.975355 0.7929309 13.71782  863.9153 1.009251

Since `mu_tau_summary` is a matrix we can pull out columns using their names:

    mu_tau_80pct <- mu_tau_summary[, c("10%", "90%")]
    print(mu_tau_80pct)

              10%      90%
    mu  1.7419720 14.30474
    tau 0.7929309 13.71782

## Sampler diagnostics

For models fit using MCMC the stanfit object will also contain the values of parameters used for the sampler. The `get_sampler_params` function can be used to access this information.

The object returned by `get_sampler_params` is a list with one component (a matrix) per chain. Each of the matrices has number of columns corresponding to the number of sampler parameters and the column names provide the parameter names. The optional argument inc_warmup (defaulting to `TRUE`) indicates whether to include the warmup period.

    sampler_params <- get_sampler_params(fit, inc_warmup = FALSE)
    sampler_params_chain1 <- sampler_params[[1]]
    colnames(sampler_params_chain1)

    [1] "accept_stat__" "stepsize__"    "treedepth__"   "n_leapfrog__"
    [5] "divergent__"   "energy__"

To do things like calculate the average value of `accept_stat__` for each chain (or the maximum value of `treedepth__` for each chain if using the NUTS algorithm, etc.) the `sapply` function is useful as it will apply the same function to each component of `sampler_params`:

    mean_accept_stat_by_chain <- sapply(sampler_params, function(x) mean(x[, "accept_stat__"]))
    print(mean_accept_stat_by_chain)

    [1] 0.8294264 0.8707689 0.8714515 0.8549241

    max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
    print(max_treedepth_by_chain)

    [1] 4 4 4 5

## Model code

The Stan program itself is also stored in the stanfit object and can be accessed using `get_stancode`:

    code <- get_stancode(fit)

The object `code` is a single string and is not very intelligible when printed:

    print(code)

    [1] "data {\n  int<lower=0> J;          // number of schools\n  real y[J];               // estimated treatment effects\n  real<lower=0> sigma[J];  // s.e. of effect estimates\n}\nparameters {\n  real mu;\n  real<lower=0> tau;\n  vector[J] eta;\n}\ntransformed parameters {\n  vector[J] theta;\n  theta = mu + tau * eta;\n}\nmodel {\n  target += normal_lpdf(eta | 0, 1);\n  target += normal_lpdf(y | theta, sigma);\n}"
    attr(,"model_name2")
    [1] "schools"

A readable version can be printed using `cat`:

    cat(code)

    data {
      int<lower=0> J;          // number of schools
      real y[J];               // estimated treatment effects
      real<lower=0> sigma[J];  // s.e. of effect estimates
    }
    parameters {
      real mu;
      real<lower=0> tau;
      vector[J] eta;
    }
    transformed parameters {
      vector[J] theta;
      theta = mu + tau * eta;
    }
    model {
      target += normal_lpdf(eta | 0, 1);
      target += normal_lpdf(y | theta, sigma);
    }

## Initial values

The `get_inits` function returns initial values as a list with one component per chain. Each component is itself a (named) list containing the initial values for each parameter for the corresponding chain:

    inits <- get_inits(fit)
    inits_chain1 <- inits[[1]]
    print(inits_chain1)

    $mu
    [1] -1.816114

    $tau
    [1] 0.2009296

    $eta
    [1]  0.62080058  1.59983405  1.94531031 -0.31126034  1.52920856  0.08217944
    [7] -1.04723954  1.18908654

    $theta
    [1] -1.691376 -1.494659 -1.425243 -1.878655 -1.508850 -1.799601 -2.026535
    [8] -1.577191

## (P)RNG seed

The `get_seed` function returns the (P)RNG seed as an integer:

    print(get_seed(fit))

    [1] 750571131

## Warmup and sampling times

The `get_elapsed_time` function returns a matrix with the warmup and sampling times for each chain:

    print(get_elapsed_time(fit))

            warmup sample
    chain:1  0.034  0.029
    chain:2  0.035  0.034
    chain:3  0.033  0.029
    chain:4  0.033  0.032