Quirine_1987
Quirine_1987

Reputation: 13

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

Upvotes: 1

Views: 683

Answers (2)

akrun
akrun

Reputation: 886938

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))

Upvotes: 1

denis
denis

Reputation: 5673

base R:

paste0(df$duration_in_seconds %/% 60,":",floor(df$duration_in_seconds %% 60))
"0:12" "0:6"  "2:20"

data:

df <- read.table(text = "case_nr    duration_in_seconds
1.         12.3
2.         6.7
3.         140.5",header = T)

Upvotes: 3

Related Questions