fitted.dynamitefit {dynamite}R Documentation

Extract Fitted Values of a Dynamite Model

Description

Fitted values for a dynamitefit object, i.e., E(y_t | newdata, \theta) where \theta contains all the model parameters. See also predict.dynamitefit() for multi-step predictions.

Usage

## S3 method for class 'dynamitefit'
fitted(object, newdata = NULL, n_draws = NULL, expand = TRUE, df = TRUE, ...)

Arguments

object

[dynamitefit]
The model fit object.

newdata

[data.frame]
Data used in predictions. If NULL (default), the data used in model estimation is used for predictions as well. There should be no new time points that were not present in the data that were used to fit the model, and no new group levels can be included.

n_draws

[integer(1)]
Number of posterior samples to use, default is NULL which uses all samples.

expand

[logical(1)]
If TRUE (the default), the output is a single data.frame containing the original newdata and the predicted values. Otherwise, a list is returned with two components, simulated and observed, where the first contains only the predicted values, and the second contains the original newdata. Setting expand to FALSE can help conserve memory because newdata is not replicated n_draws times in the output. This argument is ignored if funs are provided.

df

[logical(1)]
If TRUE (default) the output consists of data.frame objects, and data.table objects otherwise.

...

Ignored.

Value

A data.frame containing the fitted values.

See Also

Obtaining predictions predict.dynamitefit()

Examples

data.table::setDTthreads(1) # For CRAN
fitted(gaussian_example_fit, n_draws = 2L)

set.seed(1)
# Please update your rstan and StanHeaders installation before running
# on Windows
if (!identical(.Platform$OS.type, "windows")) {
  fit <- dynamite(
    dformula = obs(LakeHuron ~ 1, "gaussian") + lags(),
    data = data.frame(LakeHuron, time = seq_len(length(LakeHuron)), id = 1),
    time = "time",
    group = "id",
    chains = 1,
    refresh = 0
  )

  if (requireNamespace("dplyr") &&
    requireNamespace("tidyr") &&
    base::getRversion() >= "4.1.0") {

    # One-step ahead samples (fitted values) from the posterior
    # (first time point is fixed due to lag in the model):
    fitted(fit) |>
      dplyr::filter(time > 2) |>
      ggplot2::ggplot(ggplot2::aes(time, LakeHuron_fitted, group = .draw)) +
      ggplot2::geom_line(alpha = 0.5) +
      # observed values
      ggplot2::geom_line(ggplot2::aes(y = LakeHuron), colour = "tomato") +
      ggplot2::theme_bw()

    # Posterior predictive distribution given the first time point:
    predict(fit, type = "mean") |>
      dplyr::filter(time > 2) |>
      ggplot2::ggplot(ggplot2::aes(time, LakeHuron_mean, group = .draw)) +
      ggplot2::geom_line(alpha = 0.5) +
      # observed values
      ggplot2::geom_line(ggplot2::aes(y = LakeHuron), colour = "tomato") +
      ggplot2::theme_bw()
  }
 }



[Package dynamite version 1.4.9 Index]