1 May 2005 04:28
[Rd] RE: as.numeric method for objects of class "difftime"
<Bill.Venables <at> csiro.au>
2005-05-01 02:28:11 GMT
2005-05-01 02:28:11 GMT
I had a couple of private replies to the message below, all very
supportive of the idea. I see that where I should have looked first is
at the function difftime, the constructor (which will hardly ever be
used except by people who know about its separate existence from
Ops.POSIXt).
Thus encouraged I formally propose that a method for as.numeric be
provided that will not break existing code, but will issue a warning if
people convert from difftime to numeric without specifying a time unit
to which the resulting numerical quantity will implicitly refer.
This is the simplest acceptable solution I could think of. The code I
propose is as follows:
###
### S3 method for objects of class 'difftime'
###
as.double.difftime <- function(x, units = attr(x, "units"), ...) {
if(missing(units)) {
warning('No time units specified for conversion to numeric.\n"',
units, '" has been assumed.')
return(as.vector(x))
}
cfToSecs <- cumprod(c(secs = 1, mins = 60, hours = 60, days = 24,
weeks = 7))
if(!is.element(units, names(cfToSecs)))
stop("Unknown time units. Acceptable time units are\n\t",
paste('"', names(cfToSecs), '", ', sep = "", collapse = ""),
"only.")
as.vector(x) * (cfToSecs[attr(x, "units")]/cfToSecs[units])
(Continue reading)
RSS Feed