From Bill.Venables at csiro.au  Sat Apr 30 08:03:27 2005
From: Bill.Venables at csiro.au (Bill.Venables@csiro.au)
Date: Sat Apr 30 11:16:45 2005
Subject: [Rd] as.numeric method for objects of class "difftime"
Message-ID: <B998A44C8986644EA8029CFE6396A9241B32C5@exqld2-bne.qld.csiro.au>

I have just become painfully aware that objects of class "difftime",
generated by the difference of two POSIXct objects, carry a "units"
attribute, which flashes by when the object is printed, for example.

The pain was occasioned when I tried to turn these objects into numberic
objects for use elsewhere as a covariate.  

as.numeric(difftime object)

simply turns off the units attribute and provides a numeric object which
may represent a number of seconds or a number of days, with no warning
as to which.

I think this is an unfortunate situation, but I can't see how to rectify
it without breaking code that may rely on this quirky feature.  My
inclination is to suggest a method for as.numeric (ie for as.double)
that settles on a single unit, which for consistency with
as.numeric(POSIXct object) should probably be seconds:

as.double.difftime <- function(x, ...)
  if(attr(x, "units") == "days") as.vector(x) * 86400 else as.vector(x)

but there must now be lots of code out there that has blythely assumed
that the difference will always be a number of days and others assume it
is always seconds.

At the very least I think the help information should carry a big red
warning about this rather unusual feature.  (It may, I suppose, but I
couldn't find it.)

Comments?

Bill Venables, 
CMIS, CSIRO Laboratories, 
PO Box 120, Cleveland, Qld. 4163
AUSTRALIA
Phone:  +61 7 3826 7251  
Fax:    +61 7 3826 7304
Mobile: +61 4 1963 4642
Home:   +61 7 3286 7700
mailto:Bill.Venables@csiro.au
http://www.cmis.csiro.au/bill.venables/


[Rd] as.numeric method for objects of class "difftime"
Bill.Venables@csiro.au