0

I am trying to use as.POSIXct in R to convert a vector of characters with the following format: "YYYY/MM"

Unfortunately, I have discovered a strange error -- the following code returns NA:

as.POSIXct("2014/12", "%Y/%m")
[1] NA

When I interpret the second number as a day everything works fine:

as.POSIXct("2014/12", "%Y/%d")
[1] "2014-07-12 CDT"

If I add a third number representing a day of month, everything works fine:

as.POSIXct("2014/12/01", "%Y/%m/%d")
[1] "2014-12-01 CDT"

Anybody have any idea why I'm getting an NA for the first code chunk?

  • 1
    posix needs to know a day, you haven't given it one - you cant given it a month only - what day of the month do you want to represent? See [this answer](http://stackoverflow.com/a/6242980/3760920) – jeremycg Jul 26 '15 at 05:10
  • 1
    The first day of the month is probably fine. So I would just need to add "/01" to the end of each character string? – Patrick S. Forscher Jul 26 '15 at 05:12
  • 2
    Sure, try as.POSIXct(paste(DATE,"/01",sep=""), "%Y/%m/%d") – jeremycg Jul 26 '15 at 05:14
  • Cool, thanks. I didn't realize that as.POSIXct always expected a day. – Patrick S. Forscher Jul 26 '15 at 05:16
  • 6
    It has nothing to do with `as.POSIXct` in particular. This won't work with `as.Date` neither. R simply doesn't have a `yyyy/mm` only class. You can use the `zoo` package if you want to use one- as per the dupe link. – David Arenburg Jul 26 '15 at 05:17

0 Answers0