Convert seconds to minutes and seconds

Hi everyone,

I have a column that displays time in seconds, but I am trying to display it in minutes, seconds format.

I have looked into lubridate, but i cannot change it to minutes and seconds as it only gives me hour, minutes, seconds.

Any help would be appreciated

Best regards
Julio

Perhaps something like this?

lubridate does have the ms() function to convert a string into a minute-second period.

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

df = tibble(x = 58:87) 

df
#> # A tibble: 30 x 1
#>        x
#>    <int>
#>  1    58
#>  2    59
#>  3    60
#>  4    61
#>  5    62
#>  6    63
#>  7    64
#>  8    65
#>  9    66
#> 10    67
#> # ... with 20 more rows

df |>  
  mutate(sec = x %% 60,
         min = (x / 60) |> floor(),
         minsec = paste(min, sec),
         minsec = ms(minsec)) |> 
  select(-sec, -min, -x)
#> # A tibble: 30 x 1
#>    minsec  
#>    <Period>
#>  1 58S     
#>  2 59S     
#>  3 1M 0S   
#>  4 1M 1S   
#>  5 1M 2S   
#>  6 1M 3S   
#>  7 1M 4S   
#>  8 1M 5S   
#>  9 1M 6S   
#> 10 1M 7S   
#> # ... with 20 more rows

## write as function?

sec_to_ms = function(df, col, name = min_sec){
  
  df |>  
    mutate(sec = {{ col }} %% 60,
           min = ({{ col }} / 60) |> floor(),
           {{name}} := paste(min, sec),
           {{name}} := ms({{name}})) |> 
    select(-sec, -min, -{{ col }})
  
}

df |> 
  sec_to_ms(x)
#> # A tibble: 30 x 1
#>    minsec  
#>    <Period>
#>  1 58S     
#>  2 59S     
#>  3 1M 0S   
#>  4 1M 1S   
#>  5 1M 2S   
#>  6 1M 3S   
#>  7 1M 4S   
#>  8 1M 5S   
#>  9 1M 6S   
#> 10 1M 7S   
#> # ... with 20 more rows

Created on 2022-01-10 by the reprex package (v2.0.1)

1 Like

Thank you so much Jack.
Really helpful, and also thanks for introducing me to a new operator.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.