Search code examples
rdatetimevectorsecondsminute

R adding to a difftime vector forgets about the units


When I extend a vector of difftimes by another difftime object, then it seems that the unit of the added item is ignored and overridden without conversion:

> t = Sys.time()
> d = difftime(c((t+1), (t+61)), t)
> d
Time differences in secs
[1]  1 61

> difftime(t+61, t)
Time difference of 1.016667 mins

> d[3] = difftime(t+61, t)
> d
Time differences in secs
[1]  1.000000 61.000000  1.016667
> as.numeric(d)
[1]  1.000000 61.000000  1.016667

This is in R 3.1.0. Is there a reasonable explanation for this behavior? I just wanted to store some time differences in this way for later use and didn't expect this at all. I didn't find this documented anywhere..

Okay, for now I'm just helping myself with always specifying the unit:

> d[3] = difftime(t+61, t, unit="secs")
> d
Time differences in secs
[1]  1 61 61

Solution

  • From help("difftime")

    If units = "auto", a suitable set of units is chosen, the largest possible (excluding "weeks") in which all the absolute differences are greater than one.

    units = "auto" is the default. So for a difference of 1 and 61 seconds, if you were to choose minutes,

    difftime(c((t+1), (t+61)), t, units = "min")
    # Time differences in mins
    # [1] 0.01666667 1.01666667
    

    One of those is less than one, so by default since you did not specify the units R chose them for you according to the guidelines above. Additionally, the units are saved with the object

    d <- difftime(c((t+1), (t+61)), t)
    units(d)
    # [1] "secs"
    

    But you can change the units with units<-

    d[3] <- difftime(t+61, t)
    d
    # Time differences in mins
    # [1] 0.01666667 1.01666667 1.01666667
    units(d) <- "secs"
    d
    # Time differences in secs
    # [1]  1 61 61