Bug 15209 - difftime concatenation
Summary: difftime concatenation
Status: NEW
Alias: None
Product: R
Classification: Unclassified
Component: Language (show other bugs)
Version: R 2.15.2
Hardware: x86_64/x64/amd64 (64-bit) Windows 64-bit
: P5 major
Assignee: R-core
URL:
Depends on:
Blocks:
 
Reported: 2013-02-15 18:12 UTC by gabsalom
Modified: 2014-12-06 13:50 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description gabsalom 2013-02-15 18:12:11 UTC
Hi all,

This is my first post here. I wanted to mention a potential issue in the concatenation of difftime objects. 

The difftime function automatically selects the units returned based on the minimum absolute difference in the two time vectors. When you try and concatenate two difftime vectors, using "c()", the units are NOT taken into account. Danger!


This is probably best illustrated by an example,

vecA <- c(as.POSIXct("2013-02-11 09:00:00"),as.POSIXct("2013-02-11 10:00:00"),as.POSIXct("2013-02-11 11:00:00"))

vecB <- c(as.POSIXct("2013-02-11 09:00:00"),as.POSIXct("2013-02-11 09:10:00"),as.POSIXct("2013-02-11 09:20:00"))

c(diff(vecA),diff(vecB))

This gives a vector [1 1 10 10] when the answer is [1hour 1hour 10mins 10mins]

The way to resolve this is to do 

c(difftime(tail(vecA,-1),head(vecA,-1),units="secs"),difftime(tail(vecB,-1),head(vecB,-1),units="secs"))


For those that are aware of this, the solution is relatively simple. Yet, I would argue that most users (myself included) are not aware of this and it can lead to serious errors.

My proposed solution would be force the difftime function to return the difference in seconds only. I would question the logic in the function to convert to other units, surely it is relatively easy for users to convert seconds to other time frames as required. 

Finally, I believe giving the user the extra conversion work outweighs the dangers of concatenation. But hey, that is just my thought. It also makes the function simpler and quicker.

difftime <- function (time1, time2, tz) 
{
    if (missing(tz)) {
        time1 <- as.POSIXct(time1)
        time2 <- as.POSIXct(time2)
    }
    else {
        time1 <- as.POSIXct(time1, tz = tz)
        time2 <- as.POSIXct(time2, tz = tz)
    }
    z <- unclass(time1) - unclass(time2)
}


Thanks

Geoffrey Absalom
Comment 1 Georg Ferber 2014-12-06 13:50:31 UTC
Obviously, the problem also applies to functions like rbind, if at least one of the columns is of type difftime.