-1

I have table,

>dt
ID     Date
001   13-Jan-2016
002   2016-01-10
003   15-Jan-2016
004   2016-01-09
005   2016-01-11

and, I want to make my table like this

>dt
    ID     Date
    004   09-Jan-2016
    002   10-Jan-2016
    005   11-Jan-2016
    001   13-Jan-2016
    003   15-Jan-2016

I want to set default for the Date variable and make it order. What should I do? Thanks.

Ameerah
  • 65
  • 7

1 Answers1

3

If you have exactly the two formats you show, you can use grepl to look for letters, and use ifelse to pass as.Date a different format based on the result:

as.Date(dt$Date, ifelse(grepl('[a-z]', dt$Date), '%d-%b-%Y', '%Y-%m-%d'))
# [1] "2016-01-13" "2016-01-10" "2016-01-15" "2016-01-09" "2016-01-11"

If you overwrite dt$Date, you can use order to sort:

dt$Date <- as.Date(dt$Date, ifelse(grepl('[a-z]', dt$Date), '%d-%b-%Y', '%Y-%m-%d'))
dt[order(dt$Date),]

#    ID       Date
# 4 004 2016-01-09
# 2 002 2016-01-10
# 5 005 2016-01-11
# 1 001 2016-01-13
# 3 003 2016-01-15
alistaire
  • 42,459
  • 4
  • 77
  • 117