littleworth
littleworth

Reputation: 5169

How to convert MM::SS string to time format and then manipulate it

I have the following data frame:

library(tibble)
dat <- structure(list(title = c("Title A", "Title B", "Title C"), tm = c(
  "31:17",
  "30:28", "32:06"
)), row.names = c(NA, -3L), spec = structure(list(
  cols = list(title = structure(list(), class = c(
    "collector_character",
    "collector"
  )), tm = structure(list(), class = c(
    "collector_character",
    "collector"
  ))), default = structure(list(), class = c(
    "collector_guess",
    "collector"
  )), delim = ","
), class = "col_spec"), class = c(
  "spec_tbl_df",
  "tbl_df", "tbl", "data.frame"
))

It looks like this:

> dat
# A tibble: 3 × 2
  title   tm   
  <chr>   <chr>
1 Title A 31:17
2 Title B 30:28
3 Title C 32:06

The second column is time but as character. What I want to do is to add 5 minutes to it for every row; resulting in:

  Title A 36:17
  Title B 35:28
  Title C 37:06

The strategy is to convert tm into numeric form first. But I failed with this step

dat %>% 
  mutate(nt = hms::as_hms(as.numeric(tm) + 5))

It gave me:

  title   tm    nt    
  <chr>   <chr> <time>
1 Title A 31:17    NA 
2 Title B 30:28    NA 
3 Title C 32:06    NA 

What's the right way to do it?

Upvotes: 1

Views: 46

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Using lubridate -

library(dplyr)
library(lubridate)

dat %>% 
  mutate(tm = ms(tm) + minutes(5), 
         tm_string = sprintf('%02d:%02d', tm@minute, [email protected])) 

#  title   tm       tm_string
#  <chr>   <Period> <chr>    
#1 Title A 36M 17S  36:17    
#2 Title B 35M 28S  35:28    
#3 Title C 37M 6S   37:06    

Upvotes: 2

Related Questions