[R] seq() problem with chron
Daniel Nordlund
djnord|und @end|ng |rom gm@||@com
Thu Sep 6 09:07:02 CEST 2018
On 9/5/2018 10:00 PM, Waichler, Scott R wrote:
> Hi,
>
> I encountered the problem below where the last value in the chron vector created with seq() should have a time of 15:30, but instead has 15:15. What causes this and how can I make sure that the last value in the chron vector is the same as the "to" value in seq()?
>
> library(chron)
> dt1 <- chron("02/20/13", "00:00:00")
> dt2 <- chron("07/03/18", "15:30:00")
> dt <- seq(from=dt1, to=dt2, by=1/(24*4))
> dt[length(dt)]
> #[1] (07/03/18 15:15:00)
>
> Thanks,
> Scott Waichler
> Pacific Northwest National Laboratory
> scott.waichler using pnnl.gov
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
This is not a chron problem, it is a floating-point arithmetic problem
(basically, FAQ 7.31). You are adding incrementing by 1/96, which can't
be represent exactly in binary representation. So, when you expected
that you should get a time of 15:30, it is slightly larger and the
sequence is stopped at 15:15.
You could change dt2 to be chron("07/03/18", "15:31:00"). Or or you
could use POSIX datetimes with something like the following, where the
increment 900 is the number of seconds in 15 minutes.
dt1 <- strptime("02/20/13 00:00:00", "%m/%d/%y %H:%M:%S")
dt2 <- strptime("07/03/18 15:30:00", "%m/%d/%y %H:%M:%S")
dt <- seq(from=dt1, to=dt2, by=900)
dt[length(dt)]
There might also be some useful functions in the lubridate package.
Hope this is helpful,
Dan
--
Daniel Nordlund
Port Townsend, WA USA
More information about the R-help
mailing list