Home > Mobile >  Calculate the smallest time difference to x time, regardless of the date
Calculate the smallest time difference to x time, regardless of the date

Time:08-29

EDITED TYPO.. TIMES ARE NOW CORRECT WITH DESIRED OUTPUT

My data are are follows:

detection.time  darkest.hour
15:41:00        01:20:50
14:35:00        01:20:50
10:45:00        01:20:50
07:36:00        01:20:50
23:20:50        01:20:50

I also have a date column.

I would like to calculate the shortest time difference between detection.time and darkest hour, regardless of the date. For example, the output for detection.time 23:20:50 would be 2 hours, not 22 hours. I would like the output units to be in hours with decimal points.

My desired output is as follows:

detection.time  darkest.hour  output
15:41:00        01:20:50      9.6639
14:35:00        01:20:50      10.7639
10:45:00        01:20:50      9.4028
07:36:00        01:20:50      6.2528
23:20:50        01:20:50      2.0000

detection.time and darkest.hour are in class hms.

Thank you in advance!

CodePudding user response:

Here is one method after converting to ITime

library(dplyr)
library(data.table)
df1 <-  df1 %>%
    mutate(across(everything(), as.ITime),
     darkest.hour2 = case_when(detection.time > as.ITime('12:00:00') 
    ~darkest.hour   3600L * 24L, TRUE ~ darkest.hour),
     output = as.numeric(abs(darkest.hour2 - detection.time))/3600,
    darkest.hour2 = NULL)

-output

df1
 detection.time darkest.hour    output
1       15:41:00     01:20:50  9.663889
2       14:35:00     01:20:50 10.763889
3       10:45:00     01:20:50  9.402778
4       07:36:00     01:20:50  6.252778
5       23:20:50     01:20:50  2.000000

data

df1 <- structure(list(detection.time = c("15:41:00", "14:35:00", "10:45:00", 
"07:36:00", "23:20:50"), darkest.hour = c("01:20:50", "01:20:50", 
"01:20:50", "01:20:50", "01:20:50")), row.names = c(NA, -5L),
 class = "data.frame")

CodePudding user response:

We could also use lubridate's hms-class and a few calculations:

library(dplyr)
library(lubridate)

df1 |>
  mutate(diff   = hms(detection.time)-hms(darkest.hour),
         output = abs(as.numeric(if_else(diff > hours(12), diff-hours(24), diff))/3600)
        )

Output:

  detection.time darkest.hour         diff    output
1       15:41:00     01:20:50 14H 21M -50S  9.663889
2       14:35:00     01:20:50 13H 15M -50S 10.763889
3       10:45:00     01:20:50  9H 25M -50S  9.402778
4       07:36:00     01:20:50  6H 16M -50S  6.252778
5       23:20:50     01:20:50    22H 0M 0S  2.000000

Thanks to @akrun for the data.

  •  Tags:  
  • r
  • Related