1

This object is in character format and i would like to avoid extracting the 10 by string based functions since it is very cumbersome. If there is a way through as.Date() and some particular format, i would be happy to use that

3 Answers3

1

I've really been enjoying anydate from the anytime package lately.

Try this:

library(anytime)
format(anydate("2017-10"), "%m")
tomasu
  • 1,388
  • 9
  • 11
1

I believe this question has been asked before on SO.

As an alternative to the anytime package you may use lubridate

library(lubridate)
format(ymd("2017-10", truncated = 1L), "%m")

or with base R

format(as.Date(paste0("2017-10", "-01")), "%m")
Uwe
  • 41,420
  • 11
  • 90
  • 134
0

This converts it to a yearmon object (which represents a year and month with no day) and then extracts the month. See ?yearmon for more information.

library(zoo)

cycle(as.yearmon("2017-10"))
## [1] 10
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341