0

The data I'm trying to convert is supposed to be a date, however it is formatted as yyyymm with no separation by dashes or slashes, for example, 201701, 201702. In order to work with dates in R, I would like to have this formatted as mm/dd/yyyy, say 01/2017, 02/2017. I tried as.Date, but it couldn't do the job. Could some one help me solve this issue? Thanks in advance!

Amy
  • 11
  • 1
    Try `anytime::anydate(201701)` – zx8754 Mar 07 '17 at 21:22
  • 3
    what do you propose for the day part because Date classed objects need a day. If you don't care, then just add anything for the day and reformat without it. – Gavin Simpson Mar 07 '17 at 21:23
  • 2
    The `"yearmon"` class in the zoo package can represent objects having a year and month without a day. – G. Grothendieck Mar 07 '17 at 21:25
  • As this is now closed, I was going to suggest: `format(as.Date(paste0(dates, "01"), format = "%Y%m%d"), format = "%m/%Y")` for `dates` a character vector containing your numbers a strings. – Gavin Simpson Mar 07 '17 at 21:28
  • Welcome to SO. f you don't mind adding a generic date then `as.Date(gsub("(\\d{4})(\\d{2})","\\1-\\2-01","201701"),format="%Y-%m-%d")` might do the job. I just used gsub to format the string so that as.Date is happy :-) – DJJ Mar 07 '17 at 21:29
  • How about: `library(zoo); zoo::as.yearmon(as.character("201701"), "%Y%m")` – Edgar Santos Mar 07 '17 at 21:39

0 Answers0