firmo23
firmo23

Reputation: 8464

How can you sort a vector with different times in r?

I have a vector that includes specific times and I was wondering how can I sort it based on the hour from earliest to latest?

vect<-c("12:00:00","01:00:00","24:00:00")

Upvotes: 0

Views: 30

Answers (1)

akrun
akrun

Reputation: 887981

We can order after converting to time class

library(lubridate)
vect[order(hms(vect))]
#[1] "01:00:00" "12:00:00" "24:00:00"

If it only needs to consider the 'hour', extract the hour and order

vect[order(hour(hms(vect)))]

Or in base R

vect[order(strptime(vect, format = "%H:%M:%S"))]

Upvotes: 1

Related Questions