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.
Examples
library(dplyr)
# Basic Usage
tidyverse_cran_downloads %>%
time_apply(count, period = "1 week", .fun = mean, na.rm = TRUE)
#> # A time tibble: 6,375 × 4
#> # Index: date
#> # Groups: package [15]
#> package date count time_apply
#> <chr> <date> <dbl> <dbl>
#> 1 broom 2017-01-01 1053 1678.
#> 2 broom 2017-01-02 1481 1678.
#> 3 broom 2017-01-03 1851 1678.
#> 4 broom 2017-01-04 1947 1678.
#> 5 broom 2017-01-05 1927 1678.
#> 6 broom 2017-01-06 1948 1678.
#> 7 broom 2017-01-07 1542 1678.
#> 8 broom 2017-01-08 1479 1716
#> 9 broom 2017-01-09 2057 1716
#> 10 broom 2017-01-10 2278 1716
#> # ℹ 6,365 more rows