1

I have a time H:M:S in string format. I would like to convert it to time format and then sort that field in a descending order. I have tried the following with lubridate and dplyr, but I am unable to sort the timer column (in hms). Also, after using the hms from lubridate, the column type becomes unknown. So I dont know if this is the problem for sorting, because I also do not get the rank column from mutate. Please see a example below:

s <- c("08:30:40", "09:30:40")
df <- data.frame("clock" = s)
df
#>      clock
#> 1 08:30:40
#> 2 09:30:40

# convert string to time
library(lubridate)

df$timer <- hms(df$clock)
df
#>      clock      timer
#> 1 08:30:40 8H 30M 40S
#> 2 09:30:40 9H 30M 40S


library(dplyr)

sorted_df <- df %>% arrange(desc(timer)) %>% mutate(rank = row_number())
df
#>      clock      timer
#> 1 08:30:40 8H 30M 40S
#> 2 09:30:40 9H 30M 40S
BKS
  • 141
  • 1
  • 10

1 Answers1

0

We can wrap with as.numeric on the 'timer' and apply the desc on that output

library(dplyr)
library(lubridate)
df %>% 
    arrange(desc(as.numeric(timer))) %>%
     mutate(rank = row_number())
#     clock      timer rank
#1 09:30:40 9H 30M 40S    1
#2 08:30:40 8H 30M 40S    2
akrun
  • 874,273
  • 37
  • 540
  • 662