Reputation: 2426
I have the the date vector:
d <- c("30/5/15", "6/6/15", "23/5/15")
I would like to convert it to 2, 3, 1
with smallest rank to older and biggest to newest.
I tried rank(d)
but it looks like it makes the ranking based on days only and reverse, it returns 3, 1, 2
.
Upvotes: 2
Views: 669
Reputation: 56179
Convert to Date
class, then numeric
, then rank
:
d <- c("30/5/15", "6/6/15", "23/5/15")
rank(as.numeric(as.Date(d, "%d/%m/%y")))
#[1] 2 3 1
Suggestions from comments:
as.numeric
, as rank can handle dates. Although it might be preferable to be explicit.library(lubridate); rank(dmy(d))
Upvotes: 4
Reputation: 164
convert the data into date format and then rank it. internally date will save in numeric values. so it can rank on it.
d <- c("30/5/15", "6/6/15", "23/5/15")
rank(as.Date(d,'%d/%m/%y'))
Upvotes: 0