% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/epred_rvars.R, R/linpred_rvars.R,
%   R/predicted_rvars.R
\name{add_epred_rvars}
\alias{add_epred_rvars}
\alias{epred_rvars}
\alias{epred_rvars.default}
\alias{epred_rvars.stanreg}
\alias{epred_rvars.brmsfit}
\alias{add_linpred_rvars}
\alias{linpred_rvars}
\alias{linpred_rvars.default}
\alias{linpred_rvars.stanreg}
\alias{linpred_rvars.brmsfit}
\alias{add_predicted_rvars}
\alias{predicted_rvars}
\alias{predicted_rvars.default}
\alias{predicted_rvars.stanreg}
\alias{predicted_rvars.brmsfit}
\title{Add \code{rvar}s for the linear predictor, posterior expectation, posterior predictive, or residuals of a model to a data frame}
\usage{
add_epred_rvars(
  newdata,
  object,
  ...,
  value = ".epred",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  dpar = NULL,
  columns_to = NULL
)

epred_rvars(
  object,
  newdata,
  ...,
  value = ".epred",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  dpar = NULL,
  columns_to = NULL
)

\method{epred_rvars}{default}(
  object,
  newdata,
  ...,
  value = ".epred",
  seed = NULL,
  dpar = NULL,
  columns_to = NULL
)

\method{epred_rvars}{stanreg}(
  object,
  newdata,
  ...,
  value = ".epred",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  dpar = NULL,
  columns_to = NULL
)

\method{epred_rvars}{brmsfit}(
  object,
  newdata,
  ...,
  value = ".epred",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  dpar = NULL,
  columns_to = NULL
)

add_linpred_rvars(
  newdata,
  object,
  ...,
  value = ".linpred",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  dpar = NULL,
  columns_to = NULL
)

linpred_rvars(
  object,
  newdata,
  ...,
  value = ".linpred",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  dpar = NULL,
  columns_to = NULL
)

\method{linpred_rvars}{default}(
  object,
  newdata,
  ...,
  value = ".linpred",
  seed = NULL,
  dpar = NULL,
  columns_to = NULL
)

\method{linpred_rvars}{stanreg}(
  object,
  newdata,
  ...,
  value = ".linpred",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  dpar = NULL,
  columns_to = NULL
)

\method{linpred_rvars}{brmsfit}(
  object,
  newdata,
  ...,
  value = ".linpred",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  dpar = NULL,
  columns_to = NULL
)

add_predicted_rvars(
  newdata,
  object,
  ...,
  value = ".prediction",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  columns_to = NULL
)

predicted_rvars(
  object,
  newdata,
  ...,
  value = ".prediction",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  columns_to = NULL
)

\method{predicted_rvars}{default}(
  object,
  newdata,
  ...,
  value = ".prediction",
  seed = NULL,
  columns_to = NULL
)

\method{predicted_rvars}{stanreg}(
  object,
  newdata,
  ...,
  value = ".prediction",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  columns_to = NULL
)

\method{predicted_rvars}{brmsfit}(
  object,
  newdata,
  ...,
  value = ".prediction",
  ndraws = NULL,
  seed = NULL,
  re_formula = NULL,
  columns_to = NULL
)
}
\arguments{
\item{newdata}{Data frame to generate predictions from.}

\item{object}{A supported Bayesian model fit that can provide fits and predictions. Supported models
are listed in the second section of \link{tidybayes-models}: \emph{Models Supporting Prediction}. While other
functions in this package (like \code{\link[=spread_rvars]{spread_rvars()}}) support a wider range of models, to work with
\code{add_epred_rvars()}, \code{add_predicted_rvars()}, etc. a model must provide an interface for generating
predictions, thus more generic Bayesian modeling interfaces like \code{runjags} and \code{rstan} are not directly
supported for these functions (only wrappers around those languages that provide predictions, like \code{rstanarm}
and \code{brm}, are supported here).}

\item{...}{Additional arguments passed to the underlying prediction method for the type of
model given.}

\item{value}{The name of the output column:
\itemize{
\item for \verb{[add_]epred_rvars()}, defaults to \code{".epred"}.
\item for \verb{[add_]predicted_rvars()}, defaults to \code{".prediction"}.
\item for \verb{[add_]linpred_rvars()}, defaults to \code{".linpred"}.
}}

\item{ndraws}{The number of draws to return, or \code{NULL} to return all draws.}

\item{seed}{A seed to use when subsampling draws (i.e. when \code{ndraws} is not \code{NULL}).}

\item{re_formula}{formula containing group-level effects to be considered in the prediction.
If \code{NULL} (default), include all group-level effects; if \code{NA}, include no group-level effects.
Some model types (such as \link[brms:brmsfit-class]{brms::brmsfit} and \link[rstanarm:stanreg-objects]{rstanarm::stanreg-objects}) allow
marginalizing over grouping factors by specifying new levels of a factor in \code{newdata}. In the case of
\code{\link[brms:brm]{brms::brm()}}, you must also pass \code{allow_new_levels = TRUE} here to include new levels (see
\code{\link[brms:posterior_predict.brmsfit]{brms::posterior_predict()}}).}

\item{dpar}{For \code{add_epred_rvars()} and \code{add_linpred_rvars()}: 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 \code{brms::brm()}). If \code{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. \code{c(sigma.hat = "sigma")}
would output the \code{"sigma"} parameter from a model as a column named \code{"sigma.hat"}).
If \code{NULL} or \code{FALSE} (the default), distributional regression parameters are not included.}

\item{columns_to}{For \emph{some} models, such as ordinal, multinomial, and multivariate models (notably, \code{\link[brms:brm]{brms::brm()}} models but
\emph{not} \code{\link[rstanarm:stan_polr]{rstanarm::stan_polr()}} models), the column of predictions in the resulting data frame may include nested columns.
For example, for ordinal/multinomial models, these columns correspond to different categories of the response variable.
It may be more convenient to turn these nested columns into rows in the output; if this is desired, set
\code{columns_to} to a string representing the name of a column you would like the column names to be placed in.
In this case, a \code{.row} column will also be added to the result indicating which rows of the output
correspond to the same row in \code{newdata}.
See \code{vignette("tidy-posterior")} for examples of dealing with output ordinal models.}
}
\value{
A data frame (actually, a \link[tibble:tibble]{tibble}) equal to the input \code{newdata} with
additional columns added containing \code{\link[posterior:rvar]{rvar}}s representing the requested predictions or fits.
}
\description{
Given a data frame and a model, adds \code{\link[posterior:rvar]{rvar}}s of draws from the linear/link-level predictor,
the expectation of the posterior predictive, or the posterior predictive to
the data frame.
}
\details{
Consider a model like:

\deqn{\begin{array}{rcl}
y &\sim& \textrm{SomeDist}(\theta_1, \theta_2)\\
f_1(\theta_1) &=& \alpha_1 + \beta_1 x\\
f_2(\theta_2) &=& \alpha_2 + \beta_2 x
\end{array}}{
y ~ SomeDist(\theta_1, \theta_2),
f_1(\theta_1) = \alpha_1 + \beta_1*x,
f_2(\theta_2) = \alpha_2 + \beta_2*x
}

This model has:
\itemize{
\item an outcome variable, \eqn{y}
\item a response distribution, \eqn{\textrm{SomeDist}}{SomeDist}, having parameters \eqn{\theta_1}
(with link function \eqn{f_1}) and \eqn{\theta_2} (with link function \eqn{f_2})
\item a single predictor, \eqn{x}
\item coefficients \eqn{\alpha_1}, \eqn{\beta_1}, \eqn{\alpha_2}, and \eqn{\beta_2}
}

We fit this model to some observed data, \eqn{y_\textrm{obs}}{y_obs}, and predictors,
\eqn{x_\textrm{obs}}{x_obs}. Given new values of predictors, \eqn{x_\textrm{new}}{x_new},
supplied in the data frame \code{newdata}, the functions for posterior draws are
defined as follows:
\itemize{
\item \code{add_predicted_rvars()} adds \code{\link[posterior:rvar]{rvar}}s containing draws from the \strong{posterior predictive distribution},
\eqn{p(y_\textrm{new} | x_\textrm{new}, y_\textrm{obs})}{p(y_new | x_new, y_obs)},
to the data.
It corresponds to \code{\link[rstanarm:posterior_predict.stanreg]{rstanarm::posterior_predict()}} or \code{\link[brms:posterior_predict.brmsfit]{brms::posterior_predict()}}.
\item \code{add_epred_rvars()} adds \code{\link[posterior:rvar]{rvar}}s containing draws from the \strong{expectation of the posterior predictive
distribution}, aka the conditional expectation,
\eqn{E(y_\textrm{new} | x_\textrm{new}, y_\textrm{obs})}{E(y_new | x_new, y_obs)},
to the data.
It corresponds to \code{\link[rstanarm:posterior_linpred.stanreg]{rstanarm::posterior_epred()}} or \code{\link[brms:posterior_epred.brmsfit]{brms::posterior_epred()}}.
Not all models support this function.
\item \code{add_linpred_rvars()} adds \code{\link[posterior:rvar]{rvar}}s containing draws from the \strong{posterior linear predictors} to the data.
It corresponds to \code{\link[rstanarm:posterior_linpred.stanreg]{rstanarm::posterior_linpred()}} or \code{\link[brms:posterior_linpred.brmsfit]{brms::posterior_linpred()}}.
Depending on the model type and additional parameters passed, this may be:
\itemize{
\item The untransformed linear predictor, e.g.
\eqn{p(f_1(\theta_1) | x_\textrm{new}, y_\textrm{obs})}{p(f_1(\theta_1) | x_new, y_obs)} =
\eqn{p(\alpha_1 + \beta_1 x_\textrm{new} | x_\textrm{new}, y_\textrm{obs})}{p(\alpha_1 + \beta_1*x_new | x_new, y_obs)}.
This is returned by \code{add_linpred_rvars(transform = FALSE)} for \pkg{brms} and \pkg{rstanarm} models.
It is analogous to \code{type = "link"} in \code{\link[=predict.glm]{predict.glm()}}.
\item The inverse-link transformed linear predictor, e.g.
\eqn{p(\theta_1 | x_\textrm{new}, y_\textrm{obs})}{p(\theta_1 | x_new, y_obs)} =
\eqn{p(f_1^{-1}(\alpha_1 + \beta_1 x_\textrm{new}) | x_\textrm{new}, y_\textrm{obs})}{p(f_1^-1(\alpha_1 + \beta_1*x_new) | x_new, y_obs)}.
This is returned by \code{add_linpred_rvars(transform = TRUE)} for \pkg{brms} and \pkg{rstanarm} models.
It is analogous to \code{type = "response"} in \code{\link[=predict.glm]{predict.glm()}}.
}

\strong{NOTE:} \code{add_linpred_rvars(transform = TRUE)} and \code{add_epred_rvars()} may be equivalent but
are not guaranteed to be. They are equivalent when the expectation of the response
distribution is equal to its first parameter, i.e. when \eqn{E(y) = \theta_1}. Many
distributions have this property (e.g. Normal distributions, Bernoulli distributions),
but not all. If you want the expectation of the posterior predictive, it is best to
use \code{add_epred_rvars()} if available, and if not available, verify this property holds prior
to using \code{add_linpred_rvars()}.
}

The corresponding functions without \code{add_} as a prefix are alternate spellings
with the opposite order of the first two arguments: e.g. \code{add_predicted_rvars(newdata, object)}
versus \code{predicted_rvars(object, newdata)}. This facilitates use in data
processing pipelines that start either with a data frame or a model.

Given equal choice between the two, the spellings prefixed with \code{add_}
are preferred.
}
\examples{
\dontrun{

library(ggplot2)
library(dplyr)
library(posterior)
library(brms)
library(modelr)

theme_set(theme_light())

m_mpg = brm(mpg ~ hp * cyl, data = mtcars, family = lognormal(),
  # 1 chain / few iterations just so example runs quickly
  # do not use in practice
  chains = 1, iter = 500)

# Look at mean predictions for some cars (epred) and compare to
# the exponeniated mu parameter of the lognormal distribution (linpred).
# Notice how they are NOT the same. This is because exp(mu) for a
# lognormal distribution is equal to its median, not its mean.
mtcars \%>\%
  select(hp, cyl, mpg) \%>\%
  add_epred_rvars(m_mpg) \%>\%
  add_linpred_rvars(m_mpg, value = "mu") \%>\%
  mutate(expmu = exp(mu), .epred - expmu)

# plot intervals around conditional means (epred_rvars)
mtcars \%>\%
  group_by(cyl) \%>\%
  data_grid(hp = seq_range(hp, n = 101)) \%>\%
  add_epred_rvars(m_mpg) \%>\%
  ggplot(aes(x = hp, color = ordered(cyl), fill = ordered(cyl))) +
  stat_lineribbon(aes(dist = .epred), .width = c(.95, .8, .5), alpha = 1/3) +
  geom_point(aes(y = mpg), data = mtcars) +
  scale_color_brewer(palette = "Dark2") +
  scale_fill_brewer(palette = "Set2")

# plot posterior predictive intervals (predicted_rvars)
mtcars \%>\%
  group_by(cyl) \%>\%
  data_grid(hp = seq_range(hp, n = 101)) \%>\%
  add_predicted_rvars(m_mpg) \%>\%
  ggplot(aes(x = hp, color = ordered(cyl), fill = ordered(cyl))) +
  stat_lineribbon(aes(dist = .prediction), .width = c(.95, .8, .5), alpha = 1/3) +
  geom_point(aes(y = mpg), data = mtcars) +
  scale_color_brewer(palette = "Dark2") +
  scale_fill_brewer(palette = "Set2")

}
}
\seealso{
\code{\link[=add_predicted_draws]{add_predicted_draws()}} for the analogous functions that use a long-data-frame-of-draws
format instead of a data-frame-of-\code{\link[posterior:rvar]{rvar}}s format. See \code{\link[=spread_rvars]{spread_rvars()}} for manipulating posteriors directly.
}
\author{
Matthew Kay
}
\keyword{manip}
