Search code examples
rlubridate

Convert seconds to minutes:seconds


I have the following dataframe

case_nr    duration_in_seconds
1.         12.3
2.         6.7
3.         140.5

I'd like the following output

case_nr    duration_in_minutes_seconds
1.         00:12
2.         00:07
3.         02:20

How to achieve in R using packages:

library(dplyr)
library(lubridate)
library(stringr)

Many thanks


Solution

  • Another option is as_hms

    library(hms)
    as_hms(df1$duration_in_seconds)
    

    Or with as.ITime

    library(data.table)
    as.ITime(df1$duration_in_seconds)
    #[1] "00:00:12" "00:00:06" "00:02:20"
    

    data

    df1 <- structure(list(case_nr = c(1, 2, 3), duration_in_seconds = c(12.3, 
    6.7, 140.5)), class = "data.frame", row.names = c(NA, -3L))