Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Programming - convert numeric to MM:SS

Tags:

r

numeric

This may be a silly question, but I can't find anything on this.

I have a numeric value that represents seconds. How can I convert it to MM:SS

For example

My number is 96

Represented in MM:SS it should be 01:36.

Any help is appreciated.

like image 636
Terno Avatar asked Dec 03 '22 15:12

Terno


1 Answers

The %/% (integer division) and %% (modulo) operators are your friends:

x <- 96
paste(x %/% 60, x %% 60, sep = ":")

which gives

> paste(x %/% 60, x %% 60, sep = ":")
[1] "1:36"

Here it is in a function:

d2ms <- function(x) {
  paste(x %/% 60, x %% 60, sep = ":")
}

> xx <- c(120, 96, 45, 30)
> d2ms(xx)
[1] "2:0"  "1:36" "0:45" "0:30"

Which shows we need a little help to get exactly the format you need; see ?sprint for ways to format numbers [as characters] with leading 0s etc:

d2ms <- function(x) {
  sprintf("%02d:%02d", x %/%60, x %% 60)
}

> d2ms(xx)
[1] "02:00" "01:36" "00:45" "00:30"

Note that the : in the string above is a literal, the %xxy bits are the formats for the values specified in the next two arguments and include formatting details for the number of zeros to pad (i.e. pad with zeroes until number uses two digits.) The template for this usage here is:

%[flag][width]specifier,

where here we used:

  • 0 as the flag --- pad with 0s
  • width was 2, we want MM or SS
  • specifier was d for integers (could also have been i)

Whether you need that or not is up to your end use case.

These operators are quite useful for these sorts of operations; another example would be converting from degrees, minutes, seconds notation to decimal degrees for spatial coordinates.

like image 112
Gavin Simpson Avatar answered Dec 23 '22 17:12

Gavin Simpson