Wicelo
Wicelo

Reputation: 2426

Convert a date vector to ranks

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

Answers (2)

zx8754
zx8754

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:

  • drop as.numeric, as rank can handle dates. Although it might be preferable to be explicit.
  • use lubridate package: library(lubridate); rank(dmy(d))

Upvotes: 4

Sivaji
Sivaji

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

Related Questions