[R] c() and dates

David Winsemius dwinsemius at comcast.net
Fri Oct 3 16:58:52 CEST 2014


On Oct 3, 2014, at 7:19 AM, Therneau, Terry M., Ph.D. wrote:

> I'm a bit puzzled by a certain behavior with dates.  (R version 3.1.1)
> 
> > temp1 <- as.Date(1:2, origin="2000/5/3")
> > temp1
> [1] "2000-05-04" "2000-05-05"
> 
> > temp2 <- as.POSIXct(temp1)
> > temp2
> [1] "2000-05-03 19:00:00 CDT" "2000-05-04 19:00:00 CDT"
> 
> So far so good.  On 5/4, midnight in Greenwich it was 19:00 on 5/3 in my time zone.  The manual page has a clear explanation of what goes on.
> 
> > c(temp1, temp2)
> [1] "2000-05-04"    "2000-05-05"    "2623237-10-15" "2623474-05-06"
> > class(c(temp1, temp2))
> [1] "Date"
> 
> > c(temp2, temp1)
> [1] "2000-05-03 19:00:00 CDT" "2000-05-04 19:00:00 CDT"
> [3] "1969-12-31 21:04:41 CST" "1969-12-31 21:04:42 CST"
> > class(c(temp2, temp1))
> [1] "POSIXct" "POSIXt"
> 
> I would have expected c() to determine a common class, somehow, then do the conversion and concatonate.  That is obviously not what happens.  I've read the manual page but I must be missing something.  I make no claim that R is broken, mistaken, or otherwise deficient, only that my understanding is so.
> 
> Could someone illuminate?

Followup to my earlier post: It's pretty easy to redefine c.Date and c.POSIXct to behave in hte manner is expected:

 c.Date <- function (..., recursive = FALSE) 
   structure(c(unlist(lapply(list(...), as.Date))), class = "Date")
  temp1 <- as.Date(1:2, origin="2000/5/3")
  temp1
#[1] "2000-05-04" "2000-05-05"
  temp2 <- as.POSIXct(temp1)

  c(temp1, temp2)
#[1] "2000-05-04" "2000-05-05" "2000-05-04" "2000-05-05"
#  class(c(temp1, temp2))
#[1] "Date"
#  c(temp2, temp1)
[1] "2000-05-03 17:00:00 PDT" "2000-05-04 17:00:00 PDT" "1969-12-31 19:04:41 PST"
[4] "1969-12-31 19:04:42 PST"

 c.POSIXct <-  function (..., recursive = FALSE) 
  .POSIXct(c(unlist(lapply(list(...), as.POSIXct))))


>  c(temp1, temp2)
[1] "2000-05-04" "2000-05-05" "2000-05-04" "2000-05-05"
>  class(c(temp1, temp2))
[1] "Date"
>  c(temp2, temp1)
[1] "2000-05-03 17:00:00 PDT" "2000-05-04 17:00:00 PDT" "2000-05-03 17:00:00 PDT"
[4] "2000-05-04 17:00:00 PDT"


-- 
David Winsemius
Alameda, CA, USA



More information about the R-help mailing list