Hack-R Hack-R - 18 days ago 6
R Question

How to get POSIXct to work with ==

I've noticed that

==
doesn't seem to work with POSIXct:

a <- structure(c(1466985600, 1464652800, 1464652800, 1464652800, 1472428800,
1466985600, 1468195200, 1472428800, 1472428800, 1474848000, 1464652800,
1468195200, 1476057600, 1464652800, 1472428800, 1472428800, 1460332800,
1460332800, 1460332800, 1460332800), class = c("POSIXct", "POSIXt"
), tzone = "UTC")

a



[1] "2016-06-27 UTC" "2016-05-31 UTC" "2016-05-31 UTC" "2016-05-31 UTC" "2016-08-29 UTC" "2016-06-27 UTC" "2016-07-11 UTC"
"2016-08-29 UTC"
[9] "2016-08-29 UTC" "2016-09-26 UTC" "2016-05-31 UTC" "2016-07-11 UTC" "2016-10-10 UTC" "2016-05-31 UTC" "2016-08-29 UTC"
"2016-08-29 UTC"
[17] "2016-04-11 UTC" "2016-04-11 UTC" "2016-04-11 UTC" "2016-04-11 UTC"


table(a=="2016-06-27")



FALSE
20



table(a=="2016-06-27 UTC")



FALSE
20



table(a==as.POSIXct("2016-06-27 UTC"))



FALSE
20



table(a==as.POSIXct("2016-06-27"))



FALSE
20



a[a=="2016-06-27"]



character(0)



How can I get this to work?

This would work, but I really hope it's not my only option:

a[a==1466985600]



[1] "2016-06-27 UTC" "2016-06-27 UTC"


Answer

The time zone needs to be separate, unless specified in the format argument. Your code embeds the time zone in the string, but the default format only includes "%Y-%m-%d" and "%Y/%m/%d" , so the time zone gets cut off and defaults to the current locale. We can find the time zone of a with attr(), since it's an attribute.

table(a == as.POSIXct("2016-06-27", tz = attr(a, "tzone")))

# FALSE  TRUE 
#    18     2 
Comments