knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/README-", out.width = "100%" )
The goal of warp is to provide tooling to group dates by a variety of periods, such as: yearly, monthly, by second, by week of the month, and more.
library(warp)
You can install the release version from CRAN with:
install.package("warp")
You can install the development version from GitHub with:
# install.packages("pak") pak::pak("DavisVaughan/warp")
One of the core functions in warp is warp_distance()
, which allows you to provide a date time vector and compute the "distance" from an origin
. For example, this computes the number of months from the unix epoch.
x <- as.Date("1970-01-01") + -2:2 x warp_distance(x, period = "month")
The values that warp_distance()
returns correspond to the distance from x
to the origin
, in units defined by the period
and the width defined by every
. The origin
defaults to the unix epoch of 1970-01-01 00:00:00
in the time zone of x
, but you can change that. In this case the distances are saying that, for example, "1970-01-02"
is in the same month as the origin, and "1969-12-31"
is 1 month group away.
You can also compute daily distances. Rather than grouping by 1 day, let's lump every 2 days together, starting from the default origin
.
# Groups 1970-01-01 and 1970-01-02 together warp_distance(x, period = "day", every = 2)
You will often want to set your own origin
date. Let's shift it forward 1 to 1970-01-02
.
origin <- as.Date("1970-01-02") origin # Groups 1970-01-02 and 1970-01-03 together warp_distance(x, period = "day", every = 2, origin = origin)
Another interesting period to group by is the "mweek"
, i.e. the week of the month. Notice that days 1-7 of January 1970 are grouped into the same bucket. Also note that days 29-31 of December 1969 fell at the end of their corresponding month. This irregular week of size 3 is treated as the 5th week of that month, but the offset value of -1
is still the number of week buckets from the origin
of 1970-01-01
.
y <- as.Date("1969-12-28") + 0:14 tibble::tibble( y = y, mweek = warp_distance(y, "mweek") )
The algorithm for warp_distance()
was inspired by xts::endpoints()
.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.