[Rd] round.Date and trunc.Date not working / implemented

Jiří Moravec j|r|@c@mor@vec @end|ng |rom gm@||@com
Fri Feb 9 01:58:00 CET 2024


 > 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)))
   }

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



More information about the R-devel mailing list