Skip to contents

Convert a data.frame object from daily to monthly, from minute data to hourly, and more. This allows the user to easily aggregate data to a less granular level by taking the value from either the beginning or end of the period.

Usage

condense_period(.data, .date_var, .period = "1 day", .side = c("start", "end"))

Arguments

.data

A tbl object or data.frame

.date_var

A column containing date or date-time values. If missing, attempts to auto-detect date column.

.period

A period to condense the time series to. Time units are condensed using lubridate::floor_date() or lubridate::ceiling_date().

The value can be:

  • second

  • minute

  • hour

  • day

  • week

  • month

  • bimonth

  • quarter

  • season

  • halfyear

  • year

Arbitrary unique English abbreviations as in the lubridate::period() constructor are allowed:

  • "1 year"

  • "2 months"

  • "30 seconds"

.side

One of "start" or "end". Determines if the first observation in the period should be returned or the last.

Value

A tibble or data.frame

See also

Time-Based dplyr functions:

Examples

# Libraries
library(timetk)
library(dplyr)

# First value in each month
m4_daily %>%
    group_by(id) %>%
    condense_period(.period = "1 month")
#> .date_var is missing. Using: date
#> # A tibble: 323 × 3
#> # Groups:   id [4]
#>    id    date       value
#>    <fct> <date>     <dbl>
#>  1 D10   2014-07-03 2076.
#>  2 D10   2014-08-01 1923.
#>  3 D10   2014-09-01 1908.
#>  4 D10   2014-10-01 2049.
#>  5 D10   2014-11-01 2133.
#>  6 D10   2014-12-01 2244.
#>  7 D10   2015-01-01 2351 
#>  8 D10   2015-02-01 2286.
#>  9 D10   2015-03-01 2291.
#> 10 D10   2015-04-01 2396.
#> # … with 313 more rows
#> # ℹ Use `print(n = ...)` to see more rows

# Last value in each month
m4_daily %>%
    group_by(id) %>%
    condense_period(.period = "1 month", .side = "end")
#> .date_var is missing. Using: date
#> # A tibble: 323 × 3
#> # Groups:   id [4]
#>    id    date       value
#>    <fct> <date>     <dbl>
#>  1 D10   2014-07-31 1917.
#>  2 D10   2014-08-31 1921.
#>  3 D10   2014-09-30 2024.
#>  4 D10   2014-10-31 2130 
#>  5 D10   2014-11-30 2217.
#>  6 D10   2014-12-31 2328.
#>  7 D10   2015-01-31 2210.
#>  8 D10   2015-02-28 2293.
#>  9 D10   2015-03-31 2392.
#> 10 D10   2015-04-30 2368.
#> # … with 313 more rows
#> # ℹ Use `print(n = ...)` to see more rows