Search code examples
rdatetime-conversion

How do I convert numeric value into hours and minutes depending upon the number of digits


I have a vector which contains the time of nearest half an hour

x <- c(30,200,2200,2300)

I need to convert this into

output <- c(00:30,02:00,22:00,23:00).

I am not able to convert the values which are less than 4 digits.
Please suggest. strptime() , as.Date() throws NA for the first element.

I tried with the below Code and it did not work. Please suggest

Code:

x <- c(30,200,2200,2300)

output <- format(strptime(x,"%H%M"),"%H:%M")
output
#[1] NA      "20:00" "22:00" "23:00"

Solution

  • Yet another way using formatC

    x <- c(30, 200, 2200, 2300)
    formatC(x, width = 4, flag = "0", big.mark = ":", big.interval = 2)
    #[1] "00:30" "02:00" "22:00" "23:00"