1

I'd like to compute the successive time differences of a vector of date-time (POSIXct object) in a specific unit in R.

With difftime, there is an argument units to force the units. But that's only for two date-times. For successive differences, I use diff. But with a POSIXct object, looks like there are some automatic choice of units depending on the values of differenciated dates.

date.posixct <- seq(as.POSIXct("2021/1/1"), as.POSIXct("2021/1/10"), "days")
> date.posixct
 [1] "2021-01-01 CET" "2021-01-02 CET" "2021-01-03 CET" "2021-01-04 CET"
 [5] "2021-01-05 CET" "2021-01-06 CET" "2021-01-07 CET" "2021-01-08 CET"
 [9] "2021-01-09 CET" "2021-01-10 CET"

diff(date.posixct)
Time differences in days
[1] 1 1 1 1 1 1 1 1 1

Looks like if some differences are less than one day, it converts to seconds.

## Duplicate the first element to have a difference of 0.
date.posixct1 <- c(date.posixct[1], date.posixct)
> date.posixct1
 [1] "2021-01-01 CET" "2021-01-01 CET" "2021-01-02 CET" "2021-01-03 CET"
 [5] "2021-01-04 CET" "2021-01-05 CET" "2021-01-06 CET" "2021-01-07 CET"
 [9] "2021-01-08 CET" "2021-01-09 CET" "2021-01-10 CET"

diff(date.posixct1)
Time differences in secs
 [1]     0 86400 86400 86400 86400 86400 86400 86400 86400 86400

So how to use diff along with difftime to force the units? Help page of difftime says:

There are methods for mean and sum (via the Summary group generic), and diff via diff.default building on the "difftime" method for arithmetic, notably -.

But not sure what it means.

user3631369
  • 329
  • 1
  • 12

0 Answers0