Learn R Programming

rstanarm (version 2.9.0-3)

as.matrix.stanreg: Extract posterior sample

Description

For models fit using MCMC (algorithm="sampling"), the posterior sample is an $S$ by $P$ matrix, where $S$ is the size of the sample --- the number of post-warmup draws from the posterior distribution of the model parameters --- and $P$ is the number of parameters. If using optimization ("optimizing") or variational inference ("meanfield" or "fullrank"), there is no posterior sample but rather a $1000$ by $P$ matrix of draws from either the asymptotic multivariate Gaussian sampling distribution of the parameters or the variational approximation to the posterior distribution.

Usage

## S3 method for class 'stanreg':
as.matrix(x, ..., pars = NULL, regex_pars = NULL)

## S3 method for class 'stanreg': as.data.frame(x, ..., pars = NULL, regex_pars = NULL)

Arguments

x
A fitted model object returned by one of the rstanarm modeling functions. See stanreg-objects.
...
Ignored.
pars
An optional character vector of parameter names.
regex_pars
An optional character vector of regular expressions to use for parameter selection. regex_pars can be used in place of pars or in addition to pars. Currently, al

Value

  • A matrix or data frame, the dimensions of which depend on pars and regex_pars (if specified), as well as the model and estimation algorithm (as described above).

See Also

stanreg-methods

Examples

Run this code
# Extract posterior sample after MCMC
draws <- as.matrix(example_model)

# For example, we can see that the median of the draws for the intercept 
# is the same as the point estimate rstanarm uses
print(median(draws[, "(Intercept)"]))
print(example_model$coefficients[["(Intercept)"]])

# Extract draws from asymptotic Gaussian sampling distribution 
# after optimization
fit <- stan_glm(mpg ~ wt, data = mtcars, algorithm = "optimizing")
draws <- as.data.frame(fit)
print(colnames(draws))
print(nrow(draws)) # 1000 draws are taken

# Extract draws from variational approximation to the posterior distribution
fit2 <- update(fit, algorithm = "meanfield")
draws <- as.data.frame(fit2, pars = "wt")
print(colnames(draws))
print(nrow(draws)) # 1000 draws are taken

Run the code above in your browser using DataLab