Learn R Programming

clock (version 0.7.1)

date-rounding: Rounding: date

Description

These are Date methods for the rounding generics.

  • date_floor() rounds a date down to a multiple of the specified precision.

  • date_ceiling() rounds a date up to a multiple of the specified precision.

  • date_round() rounds up or down depending on what is closer, rounding up on ties.

The only supported rounding precisions for Dates are "day" and "week". You can group by irregular periods such as "month" or "year" by using date_group().

Usage

# S3 method for Date
date_floor(x, precision, ..., n = 1L, origin = NULL)

# S3 method for Date date_ceiling(x, precision, ..., n = 1L, origin = NULL)

# S3 method for Date date_round(x, precision, ..., n = 1L, origin = NULL)

Value

x rounded to the specified precision.

Arguments

x

[Date]

A date vector.

precision

[character(1)]

One of:

  • "week"

  • "day"

"week" is an alias for "day" with n * 7.

...

These dots are for future extensions and must be empty.

n

[positive integer(1)]

A single positive integer specifying a multiple of precision to use.

origin

[Date(1) / NULL]

An origin to start counting from. The default origin is 1970-01-01.

Details

When rounding by "week", remember that the origin determines the "week start". By default, 1970-01-01 is the implicit origin, which is a Thursday. If you would like to round by weeks with a different week start, just supply an origin on the weekday you are interested in.

Examples

Run this code
x <- as.Date("2019-03-31") + 0:5
x

# Flooring by 2 days, note that this is not tied to the current month,
# and instead counts from the specified `origin`, so groups can cross
# the month boundary
date_floor(x, "day", n = 2)

# Compare to `date_group()`, which groups by the day of the month
date_group(x, "day", n = 2)

y <- as.Date("2019-01-01") + 0:20
y

# Flooring by week uses an implicit `origin` of 1970-01-01, which
# is a Thursday
date_floor(y, "week")
as_weekday(date_floor(y, "week"))

# If you want to round by weeks with a different week start, supply an
# `origin` that falls on the weekday you care about. This uses a Monday.
origin <- as.Date("1970-01-05")
as_weekday(origin)

date_floor(y, "week", origin = origin)
as_weekday(date_floor(y, "week", origin = origin))

Run the code above in your browser using DataLab