round_date_interval: Function to round dates to arbitrary time intervals.

View source: R/round_date_interval.R

round_date_intervalR Documentation

Function to round dates to arbitrary time intervals.

Description

round_date_interval can be useful when a date, or a vector of dates, are to be rounded to intervals such as 5-seconds, 5-minutes, or 15-minutes.

Usage

round_date_interval(date, interval = "5 min", f = round)

Arguments

date

A vector of dates to be rounded.

interval

The time-interval the date is to be rounded to.

f

Rounding function to use: round, floor, or ceiling. Note that f is not quoted.

Details

round_date_interval rounds dates to the nearest arbitrary time interval unlike xts::align.time which always pushes dates to the next interval. Dates that fall in the centre of the time interval are rounded down.

round_date_interval works by first calculating an origin. This origin is the first instant of the date's hour. round_date_interval then extracts the seconds-past-the-origin and rounds this value to the interval's multiple. The rounded value and the origin are then summed and returned.

round_date_interval can be also used for rounding dates to the nearest whole second, minute, or hour. However, lubridate::round_date and related functions may be more convenient.

round_date_interval cannot deal with multiples other than seconds or minutes. Intervals such as 2 hours will not work.

The interval argument must include a number and a unit (for example: 15 seconds or 5 min). This has been done so that there is no ambiguity about the units which the date is to be rounded to.

Author(s)

Stuart K. Grange

See Also

See time_pad, round_date, round_any

Examples

## Not run: 
# A messy date vector
date_vector <- c("2015-04-09 06:25:23", "2015-04-09 06:41:27",
                 "2015-04-09 07:02:27", "2015-04-09 07:50:40")

# Parse dates
date_vector <- lubridate::ymd_hms(date_vector, tz = "UTC")

# Round dates to 15 minute intervals
round_date_interval(date_vector, "15 min")

# Round dates to 5 minute intervals
round_date_interval(date_vector, "5 mins")

# Round a single date to various second-intervals
# Parse
date <- lubridate::ymd_hms("2013-09-13 08:03:37", tz = "UTC")

# 10 seconds
round_date_interval(date, "10 sec")

# 30 seconds
round_date_interval(date, "30 sec")


## End(Not run)


skgrange/threadr documentation built on May 11, 2024, 12:16 p.m.