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

Converting numeric time (minutes or hours) to time format (HH:MM) in R

I have a simple, but tricky question in R. How do I convert numeric values given in "minutes" or "hours" to time format in HH:MM? I have been looking for solutions, but not yet found one.

Let’s say I have a vector c(100, 563, 210), and my desired output would be "1:40, 9:23, 3:30", since the numbers in the vector are given in minutes.

Thanks in advance!

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 :

With sprintf:

sprintf("%.02d:%.02d", mns %/% 60, round(mns %% 60))
#[1] "01:40" "09:23" "03:30"

Longer, but within the lubridate package, you can do:

library(lubridate)
mns <- dminutes(c(100, 563, 210)) %>% 
  seconds_to_period()
#1] "1H 40M 0S" "9H 23M 0S" "3H 30M 0S"

sprintf('%02d:%02d', hour(mns), minute(mns))
#[1] "01:40" "09:23" "03:30"
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