I'm getting a result I don't understand in R.
If I use strptime
with a year and day formatted %Y-%m (like "2009-12"), I get an NA result. But if I add a day, like "2009-12-01", and change the format string accordingly, I do get a result. Example:
> strptime("2009-12",format="%Y-%m")
[1] NA
> strptime("2009-12-03",format="%Y-%m-%d")
[1] "2009-12-03"
Why is that?
Update: The thing I'm curious about is why strptime doesn't parse a year and a month, and the reason it seems weird that it wouldn't do so is because it does parse a year only, or a year-and-a-day:
> strptime("2009",format="%Y") # year only. Works. Uses current month and day as defaults.
[1] "2009-12-02"
> strptime("2009-03",format="%Y-%d") # year and day. Works. Uses current month as default.
[1] "2009-12-03"
> strptime("2009-03",format="%Y-%m") # year and month. Doesn't work. ?
[1] NA
Update to explain why this is not a duplicate
The possible duplicate was asked a few years after this question and it is concerned with a separate API in R
: the asDate
function. This question is about a quirk of the strptime
function that as of R
3.1.3 still applies.
That seems like sensible behavior to me. As I see it, a better question would be "why does it allow you to do this: strptime("2009-03",format="%Y-%d")
?"
Here's a workaround to get what I think you're trying to achieve (i.e. a POSIXlt object with a specified month and year, but today's day):
as.POSIXlt(paste("2009-12", days(Sys.Date()), sep="-"))
I'm just guessing here. But if it takes a year and a day, it's probably taking a year and a day in the range of 1-365 (or 366 for leap years). What you could do is use paste()
and add -01
at the end to get the standard YYYY-MM-DD
format.
Here's the test I ran.
strptime("2009-123",format="%Y-%d")
returns "2009-05-12"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With