[R] What determines the unit of POSIXct differences?

jim holtman jholtman at gmail.com
Fri Sep 11 15:09:57 CEST 2009


'-' calls 'difftime' which, if you don't specify the units, makes the
following assumptions in the code:

> difftime
function (time1, time2, tz = "", units = c("auto", "secs", "mins",
    "hours", "days", "weeks"))
{
    time1 <- as.POSIXct(time1, tz = tz)
    time2 <- as.POSIXct(time2, tz = tz)
    z <- unclass(time1) - unclass(time2)
    units <- match.arg(units)
    if (units == "auto") {
        if (all(is.na(z)))
            units <- "secs"
        else {
            zz <- min(abs(z), na.rm = TRUE)
            if (is.na(zz) || zz < 60)
                units <- "secs"
            else if (zz < 3600)
                units <- "mins"
            else if (zz < 86400)
                units <- "hours"
            else units <- "days"
        }
    }
    switch(units, secs = structure(z, units = "secs", class = "difftime"),
        mins = structure(z/60, units = "mins", class = "difftime"),
        hours = structure(z/3600, units = "hours", class = "difftime"),
        days = structure(z/86400, units = "days", class = "difftime"),
        weeks = structure(z/(7 * 86400), units = "weeks", class = "difftime"))
}


You can use difftime explicitly so you can control the units.

> c(as.POSIXct('2009-09-01'), as.POSIXct('2009-10-11')) -   as.POSIXct('2009-08-31')
Time differences in days
[1]  1 41
> difftime(c(as.POSIXct('2009-09-01'), as.POSIXct('2009-10-11')), as.POSIXct('2009-08-31'), units='sec')
Time differences in secs
[1]   86400 3542400
>
>


On Fri, Sep 11, 2009 at 7:50 AM, Heinz Tuechler <tuechler at gmx.at> wrote:
> Dear All,
>
> what determines if a difference between POSIXct objects gets expressed in
> days or seconds?
> In the following example, it's sometimes seconds, sometimes days.
>
> as.POSIXct('2009-09-01') - as.POSIXct(NA)
> Time difference of NA secs
>
> c(as.POSIXct('2009-09-01'), as.POSIXct(NA)) -
>  c(as.POSIXct('2009-09-01'), as.POSIXct('2009-08-31'))
> Time differences in secs
> [1]  0 NA
>
> c(as.POSIXct('2009-09-01'), as.POSIXct(NA)) -
>  as.POSIXct('2009-08-31')
> Time differences in days
> [1]  1 NA
>
> Thanks,
> Heinz
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list