'how to convert yearmon to numbers indicating the order of date

I have a column that looks like this:

enter image description here

I want to create another column that indicates 'April 2018' is '1', 'May 2018' is '2'. I tried to use rank(), but I only got this:

data$'X1'<-rank(as.numeric(as.Date(data$MONTH)))

enter image description here



Solution 1:[1]

Package lubridate has a lot of convenience functions for handling dates. In your case:

library(lubridate)
the_date  <- 'April 2018'
paste(the_date, 'is month number',
      month(my(the_date))
      )

Note that the function name my is short for month and year, following lubridate's mnemonic function naming.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 I_O