3

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"
jay.sf
  • 60,139
  • 8
  • 53
  • 110
R06
  • 47
  • 3

4 Answers4

1

You could use sprintf, to add leading zeros.

x <- c(30, 200, 2200, 2300)
format(strptime(sprintf("%04d", x), format="%H%M"), format="%H:%M")
# [1] "00:30" "02:00" "22:00" "23:00"
jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • 1
    @R06 You're welcome! Consider to choose one answer and [**mark an answer as accepted**](https://meta.stackexchange.com/a/5235/371738). That's the way we say _thank you_ on Stack Overflow. From the moment you have +15 reputation you can also [**upvote an answer**](https://meta.stackexchange.com/a/173400/371738). – jay.sf Jul 09 '19 at 10:34
0

It seems that the number of characters in x needs to be adjusted to at least 3 characters for format string "%H%M" to understand that there is a hour in all cases.

tmp <- strptime(ifelse(nchar(x) <= 3, paste("0", x), x),"%H%M")
output <- format(tmp,"%H:%M")
output
#[1] "00:30" "02:00" "22:00" "23:00"
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
0

If you want to end up with a character string you could bypass strptime() with some regex:

sub("(\\d{2})", "\\1:", sprintf("%04d", x))
[1] "00:30" "02:00" "22:00" "23:00"
s_baldur
  • 29,441
  • 4
  • 36
  • 69
0

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"
markus
  • 25,843
  • 5
  • 39
  • 58