How do I turn "1330"
into "13:30"
, or "133000"
into "13:30:00"
? Essentially, I want to insert a colon between every pair of numbers. I'm trying to convert characters into times.
It seems like there should be a really elegant way to do this, but I can't think of it. I was thinking of using some combination of paste()
and substr()
, but an elegant solution is escaping me.
EDIT: example string that needs to be converted:
X <- c("120000", "120500", "121000", "121500", "122000", "122500", "123000") #example of noon to 12:30pm
This replaces each sequence of two characters not followed by a boundary with those same characters followed by a colon:
gsub("(..)\\B", "\\1:", X)
On the sample string it gives:
[1] "12:00:00" "12:05:00" "12:10:00" "12:15:00" "12:20:00" "12:25:00" "12:30:00"
You can use a regular expression with a positive lookahead:
gsub("(\\d{2})(?=\\d{2})", "\\1:", X, perl = TRUE)
# [1] "12:00:00" "12:05:00" "12:10:00" "12:15:00" "12:20:00" "12:25:00" "12:30:00"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With