time_collapse: Collapse a 'tbl_time' object so that all observations in a...

Description Usage Arguments Details Examples

View source: R/time_collapse.R

Description

When 'time_collapse' is used, the index of a 'tbl_time' object is altered so that all dates that fall in a period share a common date. This can be useful for further groupwise calculations.

Usage

1
2
time_collapse(.data, period = "yearly", start_date = NULL,
  as_sep_col = FALSE, ...)

Arguments

.data

A 'tbl_time' object.

period

A formula or character specification used for time-based grouping.

If a formula, e.g. '1~year', the formula is split and parsed to form the grouping period. The 'period' argument accepts a formula of the form 'multiple ~ period' allowing for flexible period grouping. The following are examples:

* 1 Year: '1~y' * 3 Months: '3~m' * 90 Days: '90~d'

Note that while shorthand is used above, an attempt is made to recognize more explicit period names such as:

* 2 Year: '2~year' / '2~years' / '2~yearly'

The 'period' argument also accepts characters that are converted to their corresponding periods. The following are accepted:

* '"yearly"' or '"y"' * '"quarterly"' or '"q"' * '"monthly"' or '"m"' * '"weekly"' or '"w"' * '"daily"' or '"d"' * '"hour"' or '"h"' * '"minute"' or '"M"' * '"second"' or '"s"'

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.

as_sep_col

Whether to keep the original index as the column '.date' or to drop it.

...

Not currently used.

Details

The date chosen as the common date for a period is always the date at the _end_ of that period.

It is often useful to use 'as_sep_col = TRUE' to keep the original dates as well.

This function respects [dplyr::group_by()] groups.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Basic functionality -------------------------------------------------------

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

# Collapse to weekly dates
time_collapse(FB, period = "weekly")

# Collapse to every other week dates
time_collapse(FB, period = 2~w)

# Collapse to weekly dates, but keep the original too
time_collapse(FB, period = "weekly", as_sep_col = TRUE)

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

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

# Collapse each group to monthly
FANG %>%
  time_collapse("monthly")

# Collapse each group to every other month
FANG %>%
  time_collapse(2~m)

DavisVaughan/tibbletime3 documentation built on May 28, 2019, 12:25 p.m.