R/ts_examples.R

#' Principal Components, Dygraphs, Forecasts, Seasonal Adjustment
#'
#' Example Functions, Generated by [ts_]. `ts_prcomp` calculates the principal
#' components of multiple time series, `ts_dygraphs` generates an interactive
#' graphical visualization, `ts_forecast` return an univariate forecast,
#' `ts_seas` the seasonally adjusted series. `ts_na_interpolation` imputes
#' missing values.
#'
#' With the exception of `ts_prcomp`, these functions depend on external
#' packages.
#'
#' @inherit ts_default
#' @param ... further arguments, passed to the underlying function. For help,
#'   consider these functions, e.g., [stats::prcomp].
#'
#' @seealso [Vignette](https://docs.ropensci.org/tsbox/articles/ts-functions.html) on how
#'   to make arbitrary functions ts-boxable.
#'
#' @examples
#' \donttest{
#' ts_plot(
#'   ts_scale(ts_c(
#'     Male = mdeaths,
#'     Female = fdeaths,
#'     `First principal compenent` = -ts_prcomp(ts_c(mdeaths, fdeaths))[, 1]
#'   )),
#'   title = "Deaths from lung diseases",
#'   subtitle = "Normalized values"
#' )
#'
#' ts_plot(ts_c(
#'   male = mdeaths, female = fdeaths,
#'   ts_forecast(ts_c(`male (fct)` = mdeaths, `female (fct)` = fdeaths))
#' ),
#' title = "Deaths from lung diseases",
#' subtitle = "Exponential smoothing forecast"
#' )
#'
#' ts_plot(
#'   `Raw series` = AirPassengers,
#'   `Adjusted series` = ts_seas(AirPassengers),
#'   title = "Airline passengers",
#'   subtitle = "X-13 seasonal adjustment"
#' )
#'
#'
#' # See ?imputeTS::na_interpolation for options
#' dta <- ts_c(mdeaths, fdeaths)
#' dta[c(1, 3, 10), c(1, 2)] <- NA
#' head(ts_na_interpolation(dta, option = "spline"))
#'
#' ts_dygraphs(ts_c(mdeaths, EuStockMarkets))
#' }
#' @export
#' @name ts_examples
ts_prcomp <- ts_(function(x, ...) predict(prcomp(x, scale = TRUE, ...)))

#' @export
#' @name ts_examples
ts_dygraphs <- ts_(dygraphs::dygraph, class = "xts", reclass = FALSE)

#' @export
#' @name ts_examples
ts_forecast <- ts_(
  function(x, ...) forecast::forecast(ts_na_omit(x), ...)$mean,
  vectorize = TRUE
)

#' @export
#' @name ts_examples
ts_seas <- ts_(
  function(x, ...) seasonal::final(seasonal::seas(x, ...)),
  vectorize = TRUE
)

#' @export
#' @name ts_examples
ts_na_interpolation <- ts_(
  function(x, ...) imputeTS::na_interpolation(x, ...)
)
christophsax/tsbox documentation built on Sept. 22, 2023, 2:35 p.m.