time_apply: Apply a function to a time series by period

View source: R/time_apply.R

time_applyR Documentation

Apply a function to a time series by period

Description

Apply a function to a time series by period

Usage

time_apply(
  data,
  target,
  period,
  .fun,
  ...,
  start_date = NULL,
  side = "end",
  clean = FALSE,
  message = TRUE
)

Arguments

data

A tibble with a date or datetime index.

target

A column to apply the function to

period

A time-based definition (e.g. "1 week"). or a numeric number of observations per frequency (e.g. 10). See tibbletime::collapse_by() for period notation.

.fun

A function to apply (e.g. median)

...

Additional parameters passed to the function, .fun

start_date

Optional argument used to specify the start date for the first group. The default is to start at the closest period boundary below the minimum date in the supplied index.

side

Whether to return the date at the beginning or the end of the new period. By default, the "end" of the period. Use "start" to change to the start of the period.

clean

Whether or not to round the collapsed index up / down to the next period boundary. The decision to round up / down is controlled by the side argument.

message

A boolean. If message = TRUE, the frequency used is output along with the units in the scale of the data.

Details

Uses a time-based period to apply functions to. This is useful in circumstances where you want to compare the observation values to aggregated values such as mean() or median() during a set time-based period. The returned output extends the length of the data frame so the differences can easily be computed.

Value

Returns a tibbletime object of class tbl_time.

Examples


library(dplyr)

data(tidyverse_cran_downloads)

# Basic Usage
tidyverse_cran_downloads %>%
    time_apply(count, period = "1 week", .fun = mean, na.rm = TRUE)


anomalize documentation built on Nov. 2, 2023, 5:13 p.m.