Home > Software design >  In R, sort column with "HH:MM AM/PM" values
In R, sort column with "HH:MM AM/PM" values

Time:06-02

We have a column in an R dataframe that looks like the dataframe below, and we are looking to sort the dataframe by these values:

zed = data.frame(start_time = c("12:10 PM", "10:10 PM", "01:15 PM", "03:10 PM", "03:37 PM", "03:40 PM", 
    "06:05 PM", "06:40 AM", "07:05 PM", "07:05 PM", "07:07 PM", "07:10 PM", 
    "07:10 PM", "08:05 PM", "08:05 PM", "08:10 PM", "01:10 PM", "01:10 PM", 
    "01:15 PM", "03:10 AM", "03:37 PM", "03:40 PM", "06:05 PM", "06:40 PM", 
    "07:05 PM", "07:05 PM", "07:07 AM", "07:10 AM", "07:10 PM", "08:05 PM", 
    "08:05 AM", "09:10 AM"), stringsAsFactors = FALSE)

> head(zed)
  start_time
1   12:10 PM
2   10:10 PM
3   01:15 PM
4   03:10 PM
5   03:37 PM
6   03:40 PM

With 12:00AM being the earliest/latest time. In the example below, 03:10 AM would be the first value and 10:10 PM would be last. Is this possible to do in R with dplyr/tidyverse? We don't necessarily need to convert these into datetime types if we can sort the strings or sort the numbers as integers. If we can convert this column into another column that is easier to sort, that would be great.

CodePudding user response:

It is just easier to convert to a datetime and then sort. No reason to reinvent the wheel.

Base R.

zed[order(as.POSIXct(zed$start_time, "%I:%M %p", tz="")), ]

dplyr

library(dplyr)
zed %>% arrange(as.POSIXct(start_time, "%I:%M %p", tz=""))
  • Related