[R] Trouble with difftime()

Adam D. I. Kramer adik at ilovebacon.org
Fri Sep 19 02:43:40 CEST 2008

Hello again,

 	I'm interested in manipulating some date objects, and have been
playing with the difftime function. I'm not sure that this is the desired

> pa$days.before.apr30 <- difftime(may01,as.POSIXct(pa$training.max,origin=as.POSIXct("1969-12-31 16:00:00",tz="PDT")),units="days")
> units(pa$days.before.apr30)
[1] "days"
> units(pa$days.before.apr30) 
[1] "days"
> range(pa$days.before.apr30,na.rm=TRUE)
Time differences in secs
[1]     1817 15723146

...the oddity being that the range is displayed in seconds, while the "unit"
attached is days. The ?difftime info says that, "If the units are changed,
the numerical value is scaled accordingly." This appears to be true, as the
numbers reported by range() do indeed correspond to the desired output *
60*60*24 (days converted to seconds).

Also, plotting a histogram via


...produces a histogram of seconds, not days.

Using as.numeric(pa$days.before.apr30) or
as.numeric(pa$days.before.apr30,units="days") to convert the difftime object
into a number both as expected, so I just used that in order to be working
(reliably) with days, but this seems like it might be a bug, so I thought I
would bring it to your attention.

Also, I spent a bit of time freaking out about the histogram being on a
scale of 1e7, so it might be wise to print a warning if a unit conversion
occurs implicitly even if this behavior is as intended.


More information about the R-help mailing list