Question
How do I convert milliseconds to minutes and seconds?
I want to convert milliseconds values in my data to minutes and seconds (in the format MM:SS e.g. a value of 1772094 should become 29:32).
The toy data looks like this:
df <- data.frame(
ID = c("ID1", "ID2", "ID3"),
duration = c(1723456, 1834537, 1945678)
)
The output I want is:
id | duration |
---|---|
ID1 | 28:43 |
ID2 | 30:35 |
ID3 | 32:26 |
I have gotten close but not perfect with the below code.
library(dplyr)
library(lubridate)
library(hms)
df2 <- df %>%
mutate(duration_ms = seconds_to_period(duration/1000)) %>%
mutate(duration_ms = hms::hms(duration_ms))
I divide my millisecond values by a thousand to turn them into seconds so they can be used by the seconds_to_period()
function in lubridate
and then format them with hms
.
But it's currently HH:MM:SS with the seconds having decimal places (not rounded).
How do I turn millisecond values into minutes and seconds values in the format MM:SS in R?