Home > OS >  sort data by date and time in R
sort data by date and time in R

Time:10-24

So I am trying to sort the values by date and time. The codes and outputs look like below:


> d=data.frame(
    t=c('2021/7/10 9:40:06','2021/7/13 17:14:59',
        '2021/7/8 17:54:41','2021/7/8 17:36:32'),
    value=c(342,353,1431,624)
   )

> d
                   t value
1  2021/7/10 9:40:06   342
2 2021/7/13 17:14:59   353
3  2021/7/8 17:54:41  1431
4  2021/7/8 17:36:32   624

> d[order(d$t),]
                   t value
1  2021/7/10 9:40:06   342
2 2021/7/13 17:14:59   353
4  2021/7/8 17:36:32   624
3  2021/7/8 17:54:41  1431

As the data was ascending ordered by t, what I expected should be like this:

1  2021/7/8 17:36:32   624
2  2021/7/8 17:54:41  1431
3  2021/7/10 9:40:06   342
4  2021/7/13 17:14:59   353

Please give me some suggestions. Thank you very much.

CodePudding user response:

library(dplyr)
library(lubridate)    
d %>% mutate(new_t = as_datetime(t)) %>% arrange(desc(new_t))

or

d %>% mutate(new_t = as_datetime(t)) %>% arrange(new_t)

CodePudding user response:

The column t is of character type, change it to POSIXct and then you can order the data.

In base R -

d <- transform(d, t = as.POSIXct(t, format = '%Y/%m/%d %T'))
d[order(d$t), ]  

Using dplyr and lubridate -

library(dplyr)
library(lubridate)

d %>%
  mutate(t = ymd_hms(t)) %>%
  arrange(t)

#                    t value
#1 2021-07-08 17:36:32   624
#2 2021-07-08 17:54:41  1431
#3 2021-07-10 09:40:06   342
#4 2021-07-13 17:14:59   353
  • Related