This is some hellish question related to floating-point approximations and timestamps in R. Get ready :) Consider this simple example:
library(tibble)
library(lubridate)
library(dplyr)
tibble(timestamp_chr1 = c('2014-01-02 01:35:50.858'),
timestamp_chr2 = c('2014-01-02 01:35:50.800')) %>%
mutate(time1 = lubridate::ymd_hms(timestamp_chr1),
time2 = lubridate::ymd_hms(timestamp_chr2),
timediff = as.numeric(time1 - time2))
# A tibble: 1 x 5
timestamp_chr1 timestamp_chr2 time1 time2 timediff
<chr> <chr> <dttm> <dttm> <dbl>
1 2014-01-02 01:35:50.858 2014-01-02 01:35:50.800 2014-01-02 01:35:50.858000 2014-01-02 01:35:50.799999 0.0580001
Here the time difference between the two timestasmps is obviously 58
milliseconds, yet R stores that with some floating-point approximation so that it appears as 0.058001
seconds.
What is the safest way to get exactly 58
milliseconds as an asnwer instead? I thought about using as.integer
(instead of as.numeric
) but I am worried about some loss of information. What can be done here?
Thanks!