[R] date comparison doesn't match value

Simon, Heather Simon.Heather at epa.gov
Tue Oct 11 19:01:38 CEST 2016


Thanks Jim and others who have responded to this post!

Jim, this is exactly what happened.  I was having some trouble with date comparisons which turned out to be a time zone conversion issue even though the two dates I was comparing both said they were EST, when you subtracted one from the other the differences was 4 hours off from what the answer should have been (i.e. one date was interpreted as GMT).  However, when I started trying to debug I compared the as.POSIXct object to a date character string.  R interpreted the character string as a numeric value that translated to sometime in the year 1309.

Thanks for everyone's help.

Cheers,
Heather

-----Original Message-----
From: Jim Lemon [mailto:drjimlemon at gmail.com] 
Sent: Saturday, October 08, 2016 6:04 AM
To: Simon, Heather <Simon.Heather at epa.gov>
Subject: Re: [R] date comparison doesn't match value

Hi Heather,
I think the problem may be that you are trying to compare a date field and a character string. R helpfully tries to wrangle the two into comparable data types. While I don't know exactly what you have done, as R for:

as.numeric(alldata$new.date.local)

and look at the value you get.

JIm


On Sat, Oct 8, 2016 at 3:41 AM, Simon, Heather <Simon.Heather at epa.gov> wrote:
> I am running into trouble when trying to compare date fields in my dataset.  When I view a field, it looks like it is a date in 2011:
>
>
>> alldata$new.date.local[1]
> [1] "2011-07-01 12:08:07 EDT"
>
> However, when I try to compare it to a character string, it seems to 
> think it is equal to sometime between the years 1310 and 1309
>
>> alldata$new.date.local[1] < "1310-01-01 00:00:00 EDT"
> [1] TRUE
>> alldata$new.date.local[1] < "1309-12-31 23:59:59 EDT"
> [1] FALSE
>
> But not exactly equal to midnight of Dec 31 in 1309, so it is not equal to any exact time:
>
>> alldata$new.date.local[1] == "1309-12-31 23:59:59 EDT"
> [1] FALSE
>> alldata$new.date.local[1] < "1309-12-31 23:59:59 EDT"
> [1] FALSE
>> alldata$new.date.local[1] > "1309-12-31 23:59:59 EDT"
> [1] TRUE
>
> Even though this date field was created using as.POSIXct from a text string, I have tried fixing this by reapplying the as.POSIXct function:
>
>>alldata$new.date.local <- as.POSIXct(alldata$new.date.local, tz = 
>>"EDT")
>
> But this does not seem to fix the problem.  When I try recreating the date from a character string I get the same behavior.  Any suggestions would be much appreciated.
>
> -Heather
>
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.


More information about the R-help mailing list