Home > Back-end >  Fill Hour-Minutes gaps in R vector
Fill Hour-Minutes gaps in R vector

Time:10-29

Suppose that I have an Hour-Minutes Variable in R, i.e.

y = c("09:05" "09:06" "09:06" "09:06" "09:06" "09:06" "09:06" "09:06" "09:07" "09:07" "09:07" "09:07" "09:07" "09:07" "09:07" "09:07" "09:07"
  "09:07" "09:07")

class(y)
[1] "POSIXlt" "POSIXt" 

I would like to find a way to fill in the gaps of the missing Hour-Minutes and keep the original repeated values i.e my output vector I would like to be of the form

y = c("00:00","00:01","00:02",....,"23:58","23:59")

Is there a smart way to do that?

CodePudding user response:

Here is an option in base R by converting to POSIXct, get the sequence, find the ones that are not in the original vector and then concatenate (c) and sort

y1 <- as.POSIXct(y, format = '%H:%M')
y2 <- seq(as.POSIXct('00:00', format = '%H:%M'), 
      as.POSIXct('23:59', format = '%H:%M'), by = 'min')
y3 <- format(sort(c(y2[!y2 %in% y1], y1)), '%H:%M')

data

y <- c("09:05", "09:06", "09:06", "09:06", "09:06", "09:06", "09:06", 
"09:06", "09:07", "09:07", "09:07", "09:07", "09:07", "09:07", 
"09:07", "09:07", "09:07", "09:07", "09:07")
  •  Tags:  
  • r
  • Related