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. Increasing adapt_delta above 0.8 may help. See
http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
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]  8.054905  8.195382  4.709720 13.093855  1.689812  4.816868
head(list_of_draws$tau)
[1]  7.864636  2.956166  8.305550  2.932008 12.694147  1.779594
head(list_of_draws$theta)
          
iterations      [,1]       [,2]      [,3]      [,4]      [,5]      [,6]
      [1,] 23.461617  2.2995573  7.412774  6.174371  8.892483 -5.921062
      [2,] 10.450039  3.6956742  6.136249 10.997944  1.064446  7.602646
      [3,] 20.632904  8.8635474 -3.041377  2.570394 -2.419330  1.368588
      [4,] 12.099713 17.0258650 13.566586 13.653543 14.541201 16.996085
      [5,]  8.359043  0.7431535 -3.429709  4.342423 -9.047235  8.802107
      [6,]  2.577514  3.8820999  2.886069  4.796525  3.073007  6.269967
          
iterations      [,7]      [,8]
      [1,]  7.254317  8.724409
      [2,]  7.588389  6.771604
      [3,]  7.560162  9.024692
      [4,] 11.003198 13.449186
      [5,] 25.174634  6.715503
      [6,]  5.923015  6.094540


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:

 [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__"    
 [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__"    
$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.519955 19.685544
      [2,] 4.701073  2.032487
      [3,] 5.795188  3.074825
      [4,] 6.866592  7.117556
      [5,] 7.518528 15.559821
      [6,] 7.282247 14.513265


Posterior summary statistics and convergence diagnostics

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

[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         7.885764572 0.13357258 5.1721083  -2.672553   4.6989419
tau        6.727002165 0.15527630 5.5602812   0.238705   2.5769736
eta[1]     0.388304907 0.01604664 0.9307714  -1.511928  -0.2247984
eta[2]     0.009043746 0.01444121 0.8775579  -1.723807  -0.5532234
eta[3]    -0.198192518 0.01504837 0.9140056  -1.973947  -0.8282105
eta[4]    -0.021341896 0.01464829 0.8721678  -1.808183  -0.5876953
eta[5]    -0.353989906 0.01486859 0.8771231  -2.054216  -0.9248967
eta[6]    -0.189137869 0.01449718 0.9023683  -1.980306  -0.7869306
eta[7]     0.326317111 0.01391802 0.8614991  -1.390724  -0.2409020
eta[8]     0.058657396 0.01503954 0.8934211  -1.720425  -0.5301083
theta[1]  11.514494512 0.16291438 8.1145604  -1.699697   6.1356856
theta[2]   7.910352353 0.09891673 6.2738353  -4.592753   3.9814529
theta[3]   5.990340195 0.13964422 7.7741785 -11.282115   1.6761195
theta[4]   7.597211726 0.10129242 6.4397885  -5.998587   3.7138287
theta[5]   5.037491736 0.11070061 6.4679664  -8.982301   1.0572950
theta[6]   6.228709157 0.11226212 6.7772051  -8.782200   2.2117678
theta[7]  10.519290729 0.11473007 6.7098375  -1.641122   6.1450841
theta[8]   8.506716597 0.12992631 7.7247405  -7.079812   4.1640923
lp__     -39.408008460 0.07566432 2.6046328 -45.145095 -40.9768019
                  50%         75%      97.5%    n_eff      Rhat
mu         7.86866584  11.2349224  17.851113 1499.342 1.0037563
tau        5.53220585   9.2752481  20.813671 1282.281 1.0016894
eta[1]     0.41117944   1.0147567   2.197281 3364.478 1.0007245
eta[2]     0.01339931   0.5803401   1.732292 3692.704 0.9999761
eta[3]    -0.19731710   0.4070192   1.608664 3689.086 1.0007263
eta[4]    -0.01721868   0.5661490   1.669629 3545.080 0.9997750
eta[5]    -0.36594053   0.2074831   1.410722 3480.017 0.9998663
eta[6]    -0.19823542   0.4081702   1.554912 3874.368 0.9998650
eta[7]     0.34410693   0.8967297   1.952114 3831.377 0.9996084
eta[8]     0.07356025   0.6512324   1.810196 3528.930 0.9996076
theta[1]  10.43987908  15.6803063  30.883766 2480.911 1.0003643
theta[2]   7.94167369  11.7976338  20.129227 4022.784 1.0007665
theta[3]   6.56191094  10.9489883  19.931550 3099.296 0.9998579
theta[4]   7.64885262  11.5619608  20.390970 4041.935 0.9999936
theta[5]   5.54156613   9.5298409  16.264737 3413.779 1.0002733
theta[6]   6.65240038  10.6687705  18.261746 3644.473 1.0004545
theta[7]   9.92672653  14.4138549  25.668696 3420.341 0.9999746
theta[8]   8.27002626  12.7092917  24.718939 3534.871 1.0011857
lp__     -39.16883785 -37.5492170 -35.030112 1184.979 1.0047629

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  7.885765 0.1335726 5.172108 1.525829 14.31178 1499.342 1.003756
tau 6.727002 0.1552763 5.560281 1.065927 14.04652 1282.281 1.001689

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.525829 14.31178
tau 1.065927 14.04652


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.

[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.8228528 0.8995023 0.8428071 0.7985171
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 5 4 5 6


Model code

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

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:

$mu
[1] 1.436758

$tau
[1] 1.499393

$eta
[1] -1.4927266 -0.4515328 -0.3727250 -1.6401834  1.8017650  1.7145738
[7]  1.0013732 -0.4046012

$theta
[1] -0.8014266  0.7597324  0.8778963 -1.0225224  4.1383121  4.0075782
[7]  2.9382100  0.8301013


(P)RNG seed

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

[1] 1390588907


Warmup and sampling times

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

          warmup   sample
chain:1 0.056072 0.043445
chain:2 0.046830 0.052788
chain:3 0.054295 0.049252
chain:4 0.054880 0.041136