[R] Weird POSIXct behaviour

Joshua Ulrich josh.m.ulrich at gmail.com
Fri Mar 30 03:53:48 CEST 2012


On Thu, Mar 29, 2012 at 3:56 PM, Worik R <worikr at gmail.com> wrote:
> I have a reproducible example of my problem below
>
> On Mon, Mar 26, 2012 at 9:22 AM, Joshua Ulrich <josh.m.ulrich at gmail.com>
> wrote:
>>
>> > Given two identical string representations of POSIXct objects, can the
>> > two
>> > objects represent different times?
>> >
>> Yes.  Here's an example (from my Ubuntu machine) of one way:
>>
>> > (t1 <- Sys.time()); (t2 <- Sys.time())+0.001; t1 == t2
>> [1] "2012-03-25 15:13:48 CDT"
>> [1] "2012-03-25 15:13:48 CDT"
>> [1] FALSE
>> > options(digits.secs=3)
>> > (t1 <- Sys.time()); (t2 <- Sys.time())+0.001; t1 == t2
>> [1] "2012-03-25 15:17:36.520 CDT"
>> [1] "2012-03-25 15:17:36.523 CDT"
>> [1] FALSE
>>
> That is interesting.  Of course POSIXct includes more than seconds.  The
> ones I have been using are rounded to seconds (I assume) so I forgot.
>
> SO I have made the effort and I think I have an example here that
> illustrates my problem.
>
> I am hoping there is an equally simple explanation, some little thing I have
> missed!
>
<snip>
>
> I am hopelessly confused.  Is there is some sort of transformation as the
> POSIXct is changed to numertic on return from sapply?
>
I removed the (not so minimal) reproducible example because you can
get the same behavior via:
> (s <- Sys.time())
[1] "2012-03-29 20:43:35 CDT"
> as.POSIXct(as.numeric(s),origin="1970-01-01")
[1] "2012-03-30 02:43:35 CDT"

sapply() attempts to simplify to an array.  Arrays can only contain an
atomic type.  POSIXct is not an atomic type, so it gets converted to
numeric.

The way to get around this is to explicitly set the timezone in your R
session (see ?timezone).  I can do this on my Ubuntu machine via:
> Sys.setenv(TZ="GMT")

Now if I run the code above again, there is no difference after
converting from POSIXct -> numeric -> POSIXct:
> (s <- Sys.time())
[1] "2012-03-30 01:45:36 GMT"
> as.POSIXct(as.numeric(s),origin="1970-01-01")
[1] "2012-03-30 01:45:36 GMT"

HTH,
--
Joshua Ulrich  |  FOSS Trading: www.fosstrading.com

R/Finance 2012: Applied Finance with R
www.RinFinance.com



More information about the R-help mailing list