Search code examples
rdplyrlubridate

00:01:30 HMS time if_else condition R


I have a column which indicates a time stamp:

[1] 00:01:30

[2] 00:02:45

.

.

.

[50] 01:02:05

I want to use these times for IF statments. I've tried to use lubridate::hms() and it works but it changes the format from: "00:01:30" to "1M 30S"

I just want the time stamp to stay at the format of "00:01:30" and to use it for conditions. for example: mutate(times = ifelse(timestamp > "00:20:31", 1, 2))

Thanks a lot!


Solution

  • Does this work:

    library(dplyr)
    library(lubridate)
    df %>% mutate( times = case_when(hms(timestamp) > hms('00:20:31') ~ 1, TRUE ~ 2))
    # A tibble: 3 x 2
      timestamp times
      <chr>     <dbl>
    1 00:01:30      2
    2 00:02:45      2
    3 01:02:05      1
    

    Data used:

    df
    # A tibble: 3 x 1
      timestamp
      <chr>    
    1 00:01:30 
    2 00:02:45 
    3 01:02:05