Given a data frame and a model, adds draws from the posterior "fit" (aka the linear/link-level predictor) or from the posterior predictions of the model to the data frame in a long format.

add_fitted_draws(newdata, model, value = ".value", ..., n = NULL,
  seed = NULL, re_formula = NULL, category = ".category",
  dpar = FALSE, scale = c("response", "linear"))

fitted_draws(model, newdata, value = ".value", ..., n = NULL,
  seed = NULL, re_formula = NULL, category = ".category",
  dpar = FALSE, scale = c("response", "linear"))

# S3 method for default
fitted_draws(model, newdata, ...)

# S3 method for stanreg
fitted_draws(model, newdata, value = ".value", ...,
  n = NULL, seed = NULL, re_formula = NULL, category = ".category",
  dpar = FALSE, scale = c("response", "linear"))

# S3 method for brmsfit
fitted_draws(model, newdata, value = ".value", ...,
  n = NULL, seed = NULL, re_formula = NULL, category = ".category",
  dpar = FALSE, scale = c("response", "linear"))

add_linpred_draws(newdata, model, value = ".value", ..., n = NULL,
  seed = NULL, re_formula = NULL, category = ".category",
  dpar = FALSE, scale = c("response", "linear"))

linpred_draws(model, newdata, value = ".value", ..., n = NULL,
  seed = NULL, re_formula = NULL, category = ".category",
  dpar = FALSE, scale = c("response", "linear"))

add_predicted_draws(newdata, model, prediction = ".prediction", ...,
  n = NULL, seed = NULL, re_formula = NULL)

predicted_draws(model, newdata, prediction = ".prediction", ...,
  n = NULL, seed = NULL, re_formula = NULL)

# S3 method for default
predicted_draws(model, newdata, ...)

# S3 method for stanreg
predicted_draws(model, newdata,
  prediction = ".prediction", ..., n = NULL, seed = NULL,
  re_formula = NULL)

# S3 method for brmsfit
predicted_draws(model, newdata,
  prediction = ".prediction", ..., n = NULL, seed = NULL,
  re_formula = NULL)

Arguments

newdata

Data frame to generate predictions from. If omitted, most model types will generate predictions from the data used to fit the model.

model

A supported Bayesian model fit that can provide fits and predictions. Supported models are listed in the second section of tidybayes-models: Models Supporting Prediction. While other functions in this package (like spread_draws) support a wider range of models, to work with add_fitted_draws and add_predicted_draws a model must provide an interface for generating predictions, thus more generic Bayesian modeling interfaces like runjags and rstan are not directly supported for these functions (only wrappers around those languages that provide predictions, like rstanarm and brm, are supported here).

value

The name of the output column for fitted_draws; default ".value".

...

Additional arguments passed to the underlying prediction method for the type of model given.

n

The number of draws per prediction / fit to return, or NULL to return all draws.

seed

A seed to use when subsampling draws (i.e. when n is not NULL).

re_formula

formula containing group-level effects to be considered in the prediction. If NULL (default), include all group-level effects; if NA, include no group-level effects. Some model types (such as brm and stanreg-objects) allow marginalizing over grouping factors by specifying new levels of a factor in newdata. In the case of brm, you must also pass allow_new_levels = TRUE here to include new levels (see predict.brmsfit).

category

For some ordinal and multinomial models (notably, brm models but not stan_polr models), multiple sets of rows will be returned per input row for fitted_draws, one for each category. The category argument specifies the name of the column to put the category names into in the resulting data frame (default: ".category"). The fact that multiple rows per response are returned only for some model types reflects the fact that tidybayes takes the approach of tidying whatever output is given to us, and the output from different modeling functions differ on this point. See vignette("tidy-brms") and vignette("tidy-rstanarm") for examples of dealing with output from ordinal models using both approaches.

dpar

For fitted_draws and add_fitted_draws: Should distributional regression parameters be included in the output? Valid only for models that support distributional regression parameters, such as submodels for variance parameters (as in brm). If TRUE, distributional regression parameters are included in the output as additional columns named after each parameter (alternative names can be provided using a list or named vector, e.g. c(sigma.hat = "sigma") would output the "sigma" parameter from a model as a column named "sigma.hat"). If FALSE (the default), distributional regression parameters are not included.

scale

Either "response" or "linear". If "response", results are returned on the scale of the response variable. If "linear", fitted values are returned on the scale of the linear predictor.

prediction

The name of the output column for predicted_draws; default ".prediction".

Value

A data frame (actually, a tibble) with a .row column (a factor grouping rows from the input newdata), .chain column (the chain each draw came from, or NA if the model does not provide chain information), .iteration column (the iteration the draw came from, or NA if the model does not provide iteration information), and a .draw column (a unique index corresponding to each draw from the distribution). In addition, fitted_draws includes a column with its name specified by the value argument (default is .value) containing draws from the (transformed) linear predictor, and predicted_draws contains a .prediction column containing draws from the posterior predictive distribution. For convenience, the resulting data frame comes grouped by the original input rows.

Details

add_fitted_draws adds draws from (possibly transformed) posterior linear predictors (or "link-level" predictors) to the data. It corresponds to posterior_linpred in rstanarm or fitted.brmsfit in brms.

add_predicted_draws adds draws from posterior predictions to the data. It corresponds to posterior_predict in rstanarm or predict.brmsfit in brms.

add_fitted_draws and fitted_draws are alternate spellings of the same function with opposite order of the first two arguments to facilitate use in data processing pipelines that start either with a data frame or a model. Similarly, add_predicted_draws and predicted_draws are alternate spellings.

Given equal choice between the two, add_fitted_draws and add_predicted_draws are the preferred spellings.

add_linpred_draws and linpred_draws are alternative spellings of fitted_draws and add_fitted_draws for consistency with rstanarm terminology (specifically posterior_linpred).

See also

Examples

library(ggplot2) library(dplyr)
#> #> Attaching package: 'dplyr'
#> The following object is masked from 'package:testthat': #> #> matches
#> The following objects are masked from 'package:stats': #> #> filter, lag
#> The following objects are masked from 'package:base': #> #> intersect, setdiff, setequal, union
if ( require("rstanarm", quietly = TRUE) && require("modelr", quietly = TRUE) ) { theme_set(theme_light()) m_mpg = stan_glm(mpg ~ hp * cyl, data = mtcars, # 1 chain / few iterations just so example runs quickly # do not use in practice chains = 1, iter = 500) # draw 100 fit lines from the posterior and overplot them mtcars %>% group_by(cyl) %>% data_grid(hp = seq_range(hp, n = 101)) %>% add_fitted_draws(m_mpg, n = 100) %>% ggplot(aes(x = hp, y = mpg, color = ordered(cyl))) + geom_line(aes(y = .value, group = paste(cyl, .draw)), alpha = 0.25) + geom_point(data = mtcars) # plot posterior predictive intervals mtcars %>% group_by(cyl) %>% data_grid(hp = seq_range(hp, n = 101)) %>% add_predicted_draws(m_mpg) %>% ggplot(aes(x = hp, y = mpg, color = ordered(cyl))) + stat_lineribbon(aes(y = .prediction), .width = c(.99, .95, .8, .5), alpha = 0.25) + geom_point(data = mtcars) + scale_fill_brewer(palette = "Greys") }
#> rstanarm (Version 2.17.4, packaged: 2018-04-13 01:51:52 UTC)
#> - Do not expect the default priors to remain the same in future rstanarm versions.
#> Thus, R scripts should specify priors explicitly, even if they are just the defaults.
#> - For execution on a local, multicore CPU with excess RAM we recommend calling
#> options(mc.cores = parallel::detectCores())
#> - Plotting theme set to bayesplot::theme_default().
#> #> SAMPLING FOR MODEL 'continuous' NOW (CHAIN 1). #> #> Gradient evaluation took 0 seconds #> 1000 transitions using 10 leapfrog steps per transition would take 0 seconds. #> Adjust your expectations accordingly! #> #> #> Iteration: 1 / 500 [ 0%] (Warmup) #> Iteration: 50 / 500 [ 10%] (Warmup) #> Iteration: 100 / 500 [ 20%] (Warmup) #> Iteration: 150 / 500 [ 30%] (Warmup) #> Iteration: 200 / 500 [ 40%] (Warmup) #> Iteration: 250 / 500 [ 50%] (Warmup) #> Iteration: 251 / 500 [ 50%] (Sampling) #> Iteration: 300 / 500 [ 60%] (Sampling) #> Iteration: 350 / 500 [ 70%] (Sampling) #> Iteration: 400 / 500 [ 80%] (Sampling) #> Iteration: 450 / 500 [ 90%] (Sampling) #> Iteration: 500 / 500 [100%] (Sampling) #> #> Elapsed Time: 0.079 seconds (Warm-up) #> 0.078 seconds (Sampling) #> 0.157 seconds (Total) #>