[Rd] round.Date and trunc.Date not working / implemented
Duncan Murdoch
murdoch@dunc@n @end|ng |rom gm@||@com
Fri Feb 9 14:36:23 CET 2024
On 08/02/2024 7:58 p.m., Jiří Moravec wrote:
> > This is a workaround, and could be the basis for a round.Date
> improvement:
> > date <- Sys.Date()
> > as.Date(round(as.POSIXct(date), "years"))
> > as.Date(round(as.POSIXct(Sys.Date() + 180), "years"))
> > Duncan Murdoch
>
> That would work, perhaps structured similarly as `trunc.Date` is.
> The only issue might be that `trunc.Date` is currently using `round.Date`
> in its numeric form likely to prevent ?expensive? conversion to POSIXt
> when it is not required.
>
> > trunc.Date
> > function (x, units = c("secs", "mins", "hours", "days", "months",
> > "years"), ...)
> > {
> > units <- match.arg(units)
> > if (units == "months" || units == "years")
> > as.Date(trunc.POSIXt(x, units, ...))
> > else round(x - 0.4999999)
> > }
>
> Perhaps the working version of `round.Date` could be:
>
> round.Date = function(x, units = c("secs", "mins", "hours", "days",
> "months", "years")){
> units = match.arg(units)
>
> if (units == "months" || units == "years")
> as.Date(round.POSIXt(x, units, ...))
> else .Date(round(as.numeric(x)))
> }
If I were writing round.Date, I wouldn't offer the user an explicit
option to round to seconds, minutes or hours. So the header could be
round.Date = function(x, units = c("days", "months", "years"))
Whether the function would complain if given other units like "secs"
would need to be decided.
Like Henrik, I don't really like direct calls to methods such as your
round.POSIXt call. Those make assumptions that may not be true for
weird corner cases where the class is not just "Date", but something
more complicated that happens to have "Date" as one of the components of
the class. However, the related functions use that writing style, so I
shouldn't complain too much.
Duncan Murdoch
>
> Or perhaps `unclass` instead of `as.numeric`. Since the default `units`
> for round(x) evaluates
> to `sec`, this should correctly skip the first condition in `round` and
> get to the correct numeric
> rounding.
>
> Perhaps the `trunc.Date` should be modified as well so that the call to
> `round.Date` is skipped in favour of internal `round.numeric`, saving
> few cycles.
>
> -- Jirka
>
> ______________________________________________
> R-devel using r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
More information about the R-devel
mailing list