r-lib / clock

A Date-Time Library for R
https://clock.r-lib.org
Other
97 stars 4 forks source link

Implement `date_expand()`, `calendar_expand()`, and `time_point_expand()` #279

Closed DavisVaughan closed 1 year ago

DavisVaughan commented 2 years ago

Similar idea to tidyr::full_seq()

Probably needs good definitions of min() and max() for all calendar / time-point types. In particular, min() and max() of empty calendar / time-point objects, which should return the max and min allowed values respectively, which are currently a little hard to define right now and are precision specific

DavisVaughan commented 2 years ago

Something like this

devtools::load_all()
#> ℹ Loading clock

calendar_expand <- function(x) {
  if (vec_size(x) == 0L) {
    x <- unname(x)
    return(x)
  }

  precision <- calendar_precision_attribute(x)
  by <- duration_helper(1L, precision = precision)

  # wrong right now if there are NAs due to CRAN vctrs xtfrm()
  x <- range(x)

  seq(from = x[[1]], to = x[[2]], by = by)
}

calendar_expand(year_month_day(2021:2022, 2))
#> <year_month_day<month>[13]>
#>  [1] "2021-02" "2021-03" "2021-04" "2021-05" "2021-06" "2021-07" "2021-08"
#>  [8] "2021-09" "2021-10" "2021-11" "2021-12" "2022-01" "2022-02"

calendar_expand(year_month_day(integer()))
#> <year_month_day<year>[0]>

Uncertain if expand is the right name for this - tidyr::expand() expands on all combinations. It doesn't fill in implicitly missing values.