About fractional days, trunc.Date2 actually seems to have no regression and to 
be backward compatible compared to the original trunc.Date:

frac <- as.Date("2020-01-01") + 0.5
identical(trunc(frac), trunc.Date2(frac))

(I may still miss something since I do not understand how trunc.Date manage 
fractional days with round(x - 0.4999999).)

-----Message d'origine-----
De : SOEIRO Thomas 
Envoyé : mercredi 29 septembre 2021 17:00
À : 'r-devel@r-project.org'
Objet : trunc.Date and round.Date + documentation of DateTimeClasses

Dear All,

1) trunc.Date and round.Date:

Currently, the help page for trunc.Date and round.Date says "The methods for 
class "Date" are of little use except to remove fractional days". However, 
e.g., trunc.POSIXt(Sys.Date(), "years") and round.POSIXt(Sys.Date(), "years") 
work because the functions start with x <- as.POSIXlt(x).

Would you consider a simple implementation of trunc.Date and round.Date based 
on trunc.POSIXt and round.POSIXt? This would enable to avoid coercion from Date 
to POSIXt and back to Date for these simple manipulations.

For example:
# (I do not have a clear understanding of what "remove fractional days" means, 
and I did not implement it.)
        
trunc.Date2 <-
  function(x, units = c("days", "months", "years"), ...)
  {
    units <- match.arg(units)
    x <- as.POSIXlt(x)
    
    switch(units,
           "days" = {
             x$sec[] <- 0; x$min[] <- 0L; x$hour[] <- 0L;
             x$isdst[] <- -1L
           },
           "months" = {
             x$sec[] <- 0; x$min[] <- 0L; x$hour[] <- 0L;
             x$mday[] <- 1L
             x$isdst[] <- -1L
           },
           "years" = {
             x$sec[] <- 0; x$min[] <- 0L; x$hour[] <- 0L;
             x$mday[] <- 1L; x$mon[] <- 0L
             x$isdst[] <- -1L
           }
    )
    as.Date(x)
  }



2) documentation of DateTimeClasses:

It may be useful to add in the documentation of DateTimeClasses that 
manipulating elements of POSIXlt objects may results in "invalid" entries 
(e.g., mon = 12 or mday = 0), but that the object is nevertheless correctly 
printed/coerced.

Is this behavior explicitly supported?

d <- as.POSIXlt("2000-01-01")
unclass(d)
d$mon <- d$mon + 12
d$mday <- d$ mday - 1
unclass(d)
d
d <- as.POSIXlt(as.POSIXct(d))
dput(d)



Best,

Thomas

______________________________________________
R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel

Reply via email to