Parse time and convert to minutes

Modular arithmetic is your friend here. Two helpful R operators:

  • %/% does integer division, e.g. 5 %/% 2 is 2 and 38 %/% 3 is 12
  • %% is the modulo/remainder opeartor, e.g. 5 %% 2 is 1 and 38 %% 3 is 2

For positive integers where m<n, we always have n = m*(n %/% m) + n %% m.

We can use that to help by recognizing the "hour" part of your input is given by x %/% 100, while the "minute" is given by x %% 100, so your answer is:

60 * (x %/% 100) + ( x %% 100 )
#    ^ hours   ^   ^ minutes  ^

You may use floor and %%.

v <- c(1245, 1345, 1805, 1950, 710, 755, 2115, 2215, 615, 730, 000)

floor(v/100)*60 + v %% 100
# [1]  765  825 1085 1190  430  475 1275 1335  375  450    0

You can try a mathematical approach, i.e.

x <- c(1245, 1345, 710, 2115, 542, 946)

(floor(x / 100) * 60) + (x - round(x, -2))
#[1]  765  825  430 1275  342  586

Tags:

Time

R