Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is parsing "%Y-%m" using strptime in R giving an NA result, but "%Y-%m-%d" works? [duplicate]

Tags:

datetime

r

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.

like image 212
bantic Avatar asked Nov 05 '22 18:11

bantic


2 Answers

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="-"))
like image 164
Shane Avatar answered Nov 11 '22 06:11

Shane


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"

like image 35
duphenix Avatar answered Nov 11 '22 05:11

duphenix