rstringtimemilliseconds

irregular sequence milliseconds transform


I have a time irregular sequence of minutes with milliseconds

msc <- c("58:49.5", "59:05.3","59:37.0", "59:50", "00:00.4", "01:41.5","03:49.5")

the transition from "59:50" to "00:00.4" means that a new hour has begun.

the vector with time may not necessarily be exactly this one and there is not always a transition to a new hour, I just showed the worst option.

The question is

How can I create a vector that will count the number of minutes and milliseconds passed from the first date to the last.

first data 58:49.5 = 00:00.0

last data 03:49.5

result vector

"00:00.0"  "00:00.1"   "00:00.2"  ........... "05:00:00"

Solution

  • First, add hours to the data

    library(lubridate)
    
    hmsc <- hours(cumsum(c(0, diff(as.numeric(ms(msc)))) < 0)) + ms(msc)
    

    then apply seq for each set of times, convert to period and then to a date time.

    Finally paste the minutes and the milliseconds. This has to be done in 2 steps because otherwise the milliseconds will have rounding errors.

    dat <- unique(unlist(
      apply(cbind(seq_along(hmsc)[-length(hmsc)],
                  seq_along(hmsc)[-1]), 1, \(x){
        Date <- as_datetime(seconds_to_period(
          seq(as.numeric(hmsc[x[1]]), as.numeric(hmsc[x[2]]), 0.1)))
     })))
    
    res <- dat - dat[1]
    
    paste0(format.Date(res, "%M:%S"), 
           sub(".*(\\..*)", "\\1", sprintf("%0.1f", res)))
    

    output

       [1] "00:00.0" "00:00.1" "00:00.2" "00:00.3" "00:00.4" "00:00.5" "00:00.6"
    ...
    [2990] "04:58.9" "04:59.0" "04:59.1" "04:59.2" "04:59.3" "04:59.4" "04:59.5"
    [2997] "04:59.6" "04:59.7" "04:59.8" "04:59.9" "05:00.0"