Eva Eva - 3 months ago 8
R Question

Strange error while converting minutes to hours

I was using the command below to convert minutes (e.g. 366) to hours and minutes format (e.g. 6:06) when I came across a strange error:

library(chron) #https://cran.r-project.org/web/packages/chron/chron.pdf

sub(":\\d{2}", "", times((X%/%60 + X%%60 /3600)/24))


I assign a vector in the place of X in the actual code, for now I will just use a number. For example:

sub(":\\d{2}", "", times((240.8%/%60 + 240.8%%60 /3600)/24))


Yields "04:01" as it should be. However, the same command with 419.8 minutes wrongly gives "6:00"?

sub(":\\d{2}", "", times((419.8%/%60 + 419.8%%60 /3600)/24))


When I re-run it without the digit, 419, it is correct again. "06:59". I re-ran the code with random numbers and it seems to be doing fine with others. I can't understand the problem. What am I doing wrong?

Answer
library(chron)
times((419.8%/%60 +  419.8%%60 /3600)/24)
# [1] 06:01:00
times((419%/%60 +  419%%60 /3600)/24)
# [1] 06:00:59

The problem is in your sub regex. Try:

sub(":\\d{2}$", "", times((419%/%60 +  419%%60 /3600)/24))
# [1] "06:00"
sub(":\\d{2}$", "", times((419.8%/%60 +  419.8%%60 /3600)/24))
# [1] "06:01"

Update:

Additionally, your math is incorrectly converting minutes to seconds. Try:

times((419.8%/%60 +  419.8%%60 / 60)/24)
# [1] 06:59:48
sub(":\\d{2}$", "", times((419.8%/%60 +  419.8%%60 / 60)/24))
# [1] "06:59"
Comments