collapse_by: Collapse a tbl_time object by its index

View source: R/collapse_index.R

collapse_byR Documentation

Collapse a tbl_time object by its index

Description

Collapse the index of a tbl_time object by time period. The index column is altered so that all dates that fall in a specified interval share a common date.

Usage

collapse_by(
  .tbl_time,
  period = "year",
  start_date = NULL,
  side = "end",
  clean = FALSE,
  ...
)

Arguments

.tbl_time

A tbl_time object.

period

A character specification used for time-based grouping. The general format to use is "frequency period" where frequency is a number like 1 or 2, and period is an interval like weekly or yearly. There must be a space between the two.

Note that you can pass the specification in a flexible way:

  • 1 Year: '1 year' / '1 Y'

This shorthand is available for year, quarter, month, day, hour, minute, second, millisecond and microsecond periodicities.

Additionally, you have the option of passing in a vector of dates to use as custom and more flexible boundaries.

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.

...

Not currently used.

Details

collapse_by() is a simplification of a call to dplyr::mutate() to collapse an index column using collapse_index().

Examples


# Basic functionality -------------------------------------------------------

# Facebook stock prices
data(FB)
FB <- as_tbl_time(FB, date)

# Collapse to weekly dates
collapse_by(FB, "weekly")

# A common workflow is to group on the collapsed date column
# to perform a time based summary
FB %>%
  collapse_by("year") %>%
  dplyr::group_by(date) %>%
  dplyr::summarise_if(is.numeric, mean)

# Grouped functionality -----------------------------------------------------

data(FANG)
FANG <- FANG %>%
  as_tbl_time(date) %>%
  dplyr::group_by(symbol)

# Collapse each group to monthly,
# calculate monthly standard deviation for each column
FANG %>%
  collapse_by("month") %>%
  dplyr::group_by(symbol, date) %>%
  dplyr::summarise_all(sd)


tibbletime documentation built on Feb. 16, 2023, 7:09 p.m.