Home > Software engineering >  Converting numeric time (minutes or hours) to time format (HH:MM) in R
Converting numeric time (minutes or hours) to time format (HH:MM) in R

Time:09-15

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!

CodePudding user response:

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