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)
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] 15.571739  6.185497  9.100040 12.893348 10.458193  5.927523
head(list_of_draws$tau)
[1] 1.506800 3.302589 3.836008 5.527944 6.435959 0.936736
head(list_of_draws$theta)
          
iterations      [,1]       [,2]      [,3]      [,4]      [,5]      [,6]
      [1,] 13.661923 13.2879965 16.388940 15.106306 14.267457 16.264776
      [2,]  4.346783 16.5594933 10.547921  7.183218  4.913907  9.694174
      [3,]  7.786241  0.3243833 11.707090 12.162921  1.492710 12.075723
      [4,] 15.588013  3.9995283 11.217721 17.456079 17.579536  6.522100
      [5,] 13.875822  5.0051332  9.380827  8.105674  5.732872  1.333129
      [6,]  4.870892  7.3454147  4.954105  5.743315  4.955600  5.669315
          
iterations      [,7]      [,8]
      [1,] 14.158221 15.444462
      [2,]  7.820992  4.889605
      [3,]  9.206248  3.239447
      [4,] 16.379690  7.488258
      [5,]  9.229843 -3.842173
      [6,]  6.938995  5.821172


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,]  4.717654 10.25667
      [2,]  4.717654 10.25667
      [3,]  9.863066 11.89045
      [4,]  7.386688 18.88754
      [5,] 14.903620 13.23784
      [6,] 11.386146 15.52720


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         7.92390241 0.09507141 4.9660621  -1.7638487   4.6673959
tau        6.49934276 0.13214508 5.4734306   0.2138296   2.4132196
eta[1]     0.39238359 0.01369181 0.9238052  -1.4199906  -0.2237536
eta[2]     0.02214772 0.01224939 0.8798969  -1.6953823  -0.5367398
eta[3]    -0.20800915 0.01451043 0.9250489  -2.0148587  -0.8224574
eta[4]    -0.02098155 0.01306533 0.8719837  -1.6988296  -0.6193309
eta[5]    -0.36491579 0.01363173 0.8833029  -2.0761602  -0.9517856
eta[6]    -0.21734807 0.01266231 0.8923120  -1.9581311  -0.8211773
eta[7]     0.35398343 0.01293481 0.8962104  -1.4335362  -0.2474079
eta[8]     0.03652631 0.01340681 0.9195589  -1.7618550  -0.5719104
theta[1]  11.28095018 0.15004741 8.2625858  -1.9138802   5.8444339
theta[2]   7.96606633 0.09235981 6.3527077  -4.9835496   4.1037550
theta[3]   6.01950245 0.12038200 7.6007933 -11.0515636   1.8931910
theta[4]   7.71231259 0.09156308 6.6065921  -6.0727134   3.7969818
theta[5]   5.03843529 0.09903682 6.3231650  -9.1342300   1.3745190
theta[6]   6.09089210 0.09574037 6.6742056  -8.7812239   2.3735130
theta[7]  10.73156655 0.09976760 6.9182286  -1.4945850   6.1306083
theta[8]   8.24074783 0.12037359 7.8274686  -7.0315216   3.8485783
lp__     -39.54920713 0.07357580 2.5858511 -45.1450973 -41.1673002
                  50%         75%      97.5%    n_eff      Rhat
mu         7.95147423  11.0970337  17.788369 2728.503 0.9998668
tau        5.28047068   8.9874233  20.403420 1715.605 1.0000755
eta[1]     0.40028773   1.0014002   2.192982 4552.386 0.9991924
eta[2]     0.01987580   0.5751354   1.795227 5159.820 0.9998670
eta[3]    -0.23375164   0.3926156   1.672872 4064.141 0.9998302
eta[4]    -0.04279697   0.5800596   1.669737 4454.263 1.0007415
eta[5]    -0.38561190   0.1867214   1.457001 4198.723 1.0002112
eta[6]    -0.21215898   0.3581979   1.595817 4966.008 0.9992948
eta[7]     0.37356667   0.9729722   2.057680 4800.645 0.9994514
eta[8]     0.03445505   0.6488414   1.836811 4704.446 1.0002089
theta[1]  10.11700312  15.3685638  31.575107 3032.319 0.9996020
theta[2]   7.80936947  11.8002066  20.893313 4730.986 0.9992605
theta[3]   6.69491918  10.6706444  20.016458 3986.527 0.9995729
theta[4]   7.73336647  11.7230892  20.802471 5206.120 0.9995731
theta[5]   5.54713106   9.2821249  16.226930 4076.389 1.0004574
theta[6]   6.47229152  10.3090674  18.468112 4859.694 0.9995915
theta[7]   9.97171260  14.8847442  26.100158 4808.513 0.9993287
theta[8]   7.92848001  12.5256846  25.496920 4228.441 0.9996103
lp__     -39.24829487 -37.7317926 -35.245813 1235.199 1.0000752

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.923902 0.09507141 4.966062 1.6982793 14.07541 2728.503 0.9998668
tau 6.499343 0.13214508 5.473431 0.9598355 13.77026 1715.605 1.0000755

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.6982793 14.07541
tau 0.9598355 13.77026


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.9202182 0.8731374 0.8971024 0.9059450
max_treedepth_by_chain <- sapply(sampler_params, function(x) max(x[, "treedepth__"]))
print(max_treedepth_by_chain)
[1] 5 5 4 4


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.231748

$tau
[1] 0.2248741

$eta
[1] -0.4651135  1.7114946 -0.1475803 -1.7394461 -1.4004020 -0.6728114
[7]  1.8746103  0.9305733

$theta
[1] 1.1271555 1.6166184 1.1985606 0.8405911 0.9168333 1.0804497 1.6532990
[8] 1.4410094


(P)RNG seed

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

print(get_seed(fit))
[1] 846061250


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.056543 0.056031
chain:2 0.049435 0.052959
chain:3 0.049836 0.051086
chain:4 0.048673 0.051781