Skip to content
Back to formatted view

Raw Message

Message-ID: <c32e4bd2-d425-44f1-b1c3-892762af1337@gmail.com>
Date: 2024-02-09T13:36:23Z
From: Duncan Murdoch
Subject: round.Date and trunc.Date not working / implemented
In-Reply-To: <8de0995f-dc5c-4788-8a8b-959bf79ee71c@gmail.com>

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 at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel