2

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
laubbas
  • 186
  • 1
  • 5

1 Answers1

0

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
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
  • Okay thanks, that makes sense. So the units are just an attribute to the vector that is not checked when I assign a new value. I guess I was expecting this assignment to be smarter - after all there is quite some type conversion when I add a string to a numeric vector. – laubbas Dec 04 '14 at 12:34
  • 1
    You can change the units with `units(d) <- "mins"` and it gets recalculated – Rich Scriven Dec 04 '14 at 12:41