Krishna Moorthy
Krishna Moorthy

Reputation: 73

Sorting or Ordering date/time columns based on Time in R

I need to sort the dataframe based on time, in time stamp column.

Here is my dput input:

structure(list(Time.stamp = structure(1:6, .Label = c("05/06/2016 21:13", 
"05/06/2016 22:52", "05/06/2016 22:58", "09/06/2016 22:40", "09/06/2016 22:45", 
"09/06/2016 22:50"), class = "factor")), .Names = "Time.stamp", class = "data.frame", row.names = c(NA, 
-6L))

My desired output is

Expected
05/06/2016            21:13
09/06/2016            22:40
09/06/2016            22:45
09/06/2016            22:50
05/06/2016            22:52
05/06/2016            22:58

I tried lubricate package,

data = dmy_hm(data$Time.stamp)   
data2 = arrange(data,f_device_time_new)

But it doesnt work. Can anyone provide some suggestion?

Upvotes: 0

Views: 1634

Answers (1)

AntoniosK
AntoniosK

Reputation: 16121

One possible solution is this:

data = structure(list(Time.stamp = structure(1:6, .Label = c("05/06/2016 21:13", 
"05/06/2016 22:52", "05/06/2016 22:58", "09/06/2016 22:40", "09/06/2016 22:45", 
"09/06/2016 22:50"), class = "factor")), .Names = "Time.stamp", class = "data.frame", row.names = c(NA, 
-6L))

library(dplyr)
library(lubridate)

data %>%
  mutate(Time.stamp = dmy_hm(Time.stamp),
         hour = hour(Time.stamp),
         min = minute(Time.stamp),
         sec = second(Time.stamp)) %>%
  arrange(hour, min, sec) %>%
  select(Time.stamp)

#   Time.stamp
# 1 2016-06-05 21:13:00
# 2 2016-06-09 22:40:00
# 3 2016-06-09 22:45:00
# 4 2016-06-09 22:50:00
# 5 2016-06-05 22:52:00
# 6 2016-06-05 22:58:00

Note that in your case you don't need the sec column, but I'm posting a more general solution.

Upvotes: 1

Related Questions