Search code examples
rtimeradix

Another POSIXlt quandary in R


Every once in a while I find a real head scratcher... Any ideas what is going on here?

> a = strptime("2003-11-01", "%Y-%m-%d")
> b = strptime("2004-01-31", "%Y-%m-%d")
> unlist(a)
  sec   min  hour  mday   mon  year  wday  yday isdst 
    0     0     0     1    10   103     6   304     0 
> unlist(b)
  sec   min  hour  mday   mon  year  wday  yday isdst 
    0     0     0    31     0   104     6    30     0 
> a$mon = a$mon-1
> b$mon = b$mon-1
> a=as.POSIXlt(as.POSIXct(a))
> b=as.POSIXlt(as.POSIXct(b))
> a
[1] NA
> b
[1] "2003-12-31 PST"
> unlist(a)
  sec   min  hour  mday   mon  year  wday  yday isdst 
   NA    NA    NA    NA    NA    NA    NA    NA    -1 
> unlist(b)
  sec   min  hour  mday   mon  year  wday  yday isdst 
    0     0     0    31    11   103     3   364     0 

Why can I edit b but not a? I feel like I must be missing something.


Solution

  • This (a) works for me with the R and session details as below:

    > a$mon = a$mon-1
    > a=as.POSIXlt(as.POSIXct(a))
    > a
    [1] "2003-10-01 01:00:00 BST"
    > unlist(a)
      sec   min  hour  mday   mon  year  wday  yday isdst 
        0     0     1     1     9   103     3   273     1
    

    Without any further information as per your locale and time zone settings etc, I would have to guess that in your locale/time zone that the date/time indicated by a after you subtracted 1 from the $mon element didn't exist. R is pretty clever about these things but time zones and locales often catch people out.

    The real question is why are you using a date/time object when you are handling just dates? a <- as.Date("2003-11-01", "%Y-%m-%d") would be sufficient in this example.

    Details of my R session:

    > sessionInfo()
    R version 2.15.0 Patched (2012-04-14 r59019)
    Platform: x86_64-unknown-linux-gnu (64-bit)
    
    locale:
     [1] LC_CTYPE=en_GB.utf8       LC_NUMERIC=C             
     [3] LC_TIME=en_GB.utf8        LC_COLLATE=en_GB.utf8    
     [5] LC_MONETARY=en_GB.utf8    LC_MESSAGES=en_GB.utf8   
     [7] LC_PAPER=C                LC_NAME=C                
     [9] LC_ADDRESS=C              LC_TELEPHONE=C           
    [11] LC_MEASUREMENT=en_GB.utf8 LC_IDENTIFICATION=C      
    
    attached base packages:
    [1] stats     graphics  grDevices utils     datasets  methods  
    [7] base     
    
    other attached packages:
    [1] ggplot2_0.9.1
    
    loaded via a namespace (and not attached):
     [1] colorspace_1.1-1   dichromat_1.2-4    digest_0.5.2      
     [4] grid_2.15.0        labeling_0.1       MASS_7.3-18       
     [7] memoise_0.1        munsell_0.3        plyr_1.7.1        
    [10] proto_0.3-9.2      RColorBrewer_1.0-5 reshape2_1.2.1    
    [13] scales_0.2.1       stringr_0.6        tools_2.15.0