Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert numbers to HH:MM in R

I’m working with a dataset with a time column in the following format:

Time 
330 
2230 
5 
45 

I want to convert this to hh:mm format

Time 
03:30 
22:30 
00:05 
00:45 

I’m new to R and I’m wondering if there’s an easy way to do this.
Any help would be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can pad the time strings to 4-digit with "0" on the left, then split the padded strins into HH:MM.

df <- data.frame(Time = c(330, 2230, 5, 45))

# solution 1
df$Time2 <- sub("(.{2})(.+)", "\\1:\\2", sprintf("%04d", df$Time))

# solution 2
df$Time2 <- format(strptime(sprintf("%04d", df$Time), "%H%M"), "%H:%M")

df
#   Time Time2
# 1  330 03:30
# 2 2230 22:30
# 3    5 00:05
# 4   45 00:45
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading