I have a vector of day numbers (1-365, 366 on leap years) and years, and I am using parse_date_time() in lubridate to convert these into a vector of dates, in yyyy-mm-dd format. I am running into issues with Dec. 31 of leap years, as the function does not seem to understand which years are leap years, and yields NAs (and other dates after Feb are offset by a year). I am trying to figure out how to get these dates to parse properly.
Here's the code I'm working with:
>parse_date_time(366,2004, order = "j", tz="UTC")
[1] NA
Warning message:
1 failed to parse.
And here is an example of what happens when the date parses properly (for non-leap-years):
> parse_date_time(336,2005, order = "j", tz="UTC")
[1] "2023-12-02 UTC"
I know lubridate has a leap_year() function, but this is for dates already in a date format, so it won't work in this case.
EDIT: Just for clarity's sake, because I did not give my example in vectors, as I described, here is an example using the answer, with days and years as vectors:
> j<-c(4,342,366)
> y<-c(2013,2015,2012)
> parse_date_time(paste(j,y), order = "j,Y", tz="UTC")%>%as_datetime()
[1] "2013-01-04 UTC" "2015-12-08 UTC" "2012-12-31 UTC"
Note that with the second example, it doesn't actually give you a datetime in 2005 - it ignores the second argument, and defaults to the current year, 2023, which isn't a leapyear, hence it failing.
The solution is to give your datetime (or date) as a string, and then it will give the correct answer:
> parse_date_time("366,2004", order = "j,Y", tz="UTC")
[1] "2004-12-31 UTC"