Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate strings into groups of 2 characters separated by colon (1330 to 13:30) in R

Tags:

regex

r

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
like image 377
rbatt Avatar asked May 09 '13 01:05

rbatt


2 Answers

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"
like image 70
G. Grothendieck Avatar answered Sep 27 '22 18:09

G. Grothendieck


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"
like image 35
flodel Avatar answered Sep 27 '22 17:09

flodel