DJD
DJD

Reputation: 83

Why are my dates not equivalent in R when they look identical?

I have two dates in R - that have been created by rounding other dates to the nearest month start using lubridate::floor_date

They look identical under all sorts of tests... e.g.

ymd(changes3$M[32]) [1] "2020-08-01" ymd(changes3$M[33]) [1] "2022-08-01"

as.POSIXct(changes3$M[33]) [1] "2022-08-01 01:00:00 BST" as.POSIXct(changes3$M[32]) [1] "2020-08-01 01:00:00 BST"

but I cannot make them perform as equivalent e.g.

changes3$M[32]==changes3$M[33] [1] FALSE

as.POSIXct(changes3$M[32])==as.POSIXct(changes3$M[33]) [1] FALSE

round_date(as.POSIXct(changes3$M[32],day))==round_date(as.POSIXct(changes3$M[33],day)) [1] FALSE

format(changes3$M[33],"%Y%M")==format(changes3$M[32],"%Y%M") [1] FALSE

What might be going wrong? When I test them against themselves these methods work OK e.g.

as.POSIXct(changes3$M[32])==as.POSIXct(changes3$M[32]) [1] TRUE

Upvotes: 1

Views: 320

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368261

That is a variant of R FAQ 7.31 as datetime objects really are floating point valued. The fact that a formatted display is equal only means that you are (implicitly) truncating -- you need to make that implicit.

> now <- Sys.time(); notnow <- Sys.time()  # so microseconds apart
> format(now) == format(notnow)            # "looks the same"
[1] TRUE
> trunc(now) == trunc(notnow)              # "equal if truncated"
[1] TRUE
> round(now) == round(notnow)              # "equal if rounded"
[1] TRUE
> 
> now == notnow                            # but not equal numerically
[1] FALSE
> 

While this may be a little irritating to work with, it is actually a feature as it gives some high(-ish) precision date and time comparison.

Upvotes: 2

Related Questions