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
Asked
Active
Viewed 460 times
1
-
This may help: https://stackoverflow.com/questions/6242955/converting-year-and-month-yyyy-mm-format-to-a-date – jjl Dec 01 '17 at 16:34
-
Because 6,7 is not generic. Month could be 5 as well as 12 – Abhay Saini Dec 01 '17 at 16:38
-
The least cumbersome would probably just be a regex that captures all digits from "-" to the end. – joran Dec 01 '17 at 16:40
-
1library(stringr); str_extract("2010-10", pattern = "[0-1]?[0-9]$") – jjl Dec 01 '17 at 16:42
3 Answers
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