Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In R, sort column with "HH:MM AM/PM" values

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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=""))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading