farhanhubble
farhanhubble

Reputation: 494

Comparing POSIXlt object with date string the right thing?

I recently came across R code that compared a POSIXlt date object with a date string.

as.POSIXlt.date("2007-02-02") >= "2007-02-01"
[1] FALSE

The result, surprisingly at least for me, was FALSE. I was expecting that the POSIXlt object would be coerced in to a character vector and so the inequality should test TRUE. I then tried explicit coercion and coercing either side in to the other's type yielded true.

as.character(as.POSIXlt.date("2007-02-02")) >= "2007-02-01"
[1] TRUE

and

as.POSIXlt.date("2007-02-02") >= as.POSIXlt.date("2007-02-01")
[1] TRUE

I think coercing the LHS date object to a character vector is semantically wrong because the comparison then would be lexicographic which is not what is intended (although it evaluates to TRUE in this case). Am I right?

In my opinion third expression is semantically right code. But why does the first code not work (it evaluates to FALSE)? Doesn't R coerce both sides to character vectors before comparing them?

Here's my platform information:

R version 3.1.0 (2014-04-10) -- "Spring Dance"
Platform: x86_64-redhat-linux-gnu (64-bit)

I am new to R. Any help is much appreciated.

Thanks, Farhan

Upvotes: 6

Views: 2123

Answers (1)

Andre Wildberg
Andre Wildberg

Reputation: 19163

In general, dates should all be of class Date when doing comparisons.

It works in some cases because R converts the String "2007-02-01" into a Date behind the scenes, which can fail in some cases:

as.Date("2020-09-12") <= "2020:09:13"
# Error in charToDate(x) : 
#   character string is not in a standard unambiguous format

Also, be aware of the different Date methods, which are incompatible:

as.POSIXlt("2007-02-02") <= as.Date("2020,01,12", "%Y,%m,%d")
#   sec    min   hour   mday    mon   year   wday   yday  isdst   zone gmtoff 
#  TRUE   TRUE   TRUE   TRUE   TRUE   TRUE   TRUE   TRUE   TRUE     NA     NA 
#Warning messages:
#1: Incompatible methods ("Ops.POSIXt", "Ops.Date") for "<=" 
#2: NAs introduced by coercion 

Btw, I can't reproduce the first example anymore (R version 4.0.3):

as.POSIXlt.date("2007-02-02") >= "2007-02-01"
# Error in as.POSIXlt.date("2007-02-02") : 
#   could not find function "as.POSIXlt.date"

as.POSIXlt.Date("2007-02-02") >= "2007-02-01"
# [1] NA
# Warning message:
# In as.POSIXlt.Date("2007-02-02") : NAs introduced by coercion

Upvotes: 1

Related Questions