Reputation: 155
I am using a package in R called midasr which helps me forecast monthly data using daily data as a regressor. For this purpose I need to make sure each month in a given year has an equal number of days. For example on months like February where it never goes to the 30th or the 31st day, I need to still be able to specify a value (NA) for that date, so as to maintain a consistent format. When I try specifying dates that never occur in real life, (2009 is a non leap year, so day 29 doesnt happen) I get an NA under the date column as follows. Is there a way to work around this? I need it to show '2009-02-29'.
> as.Date('2009-02-29', format="%Y-%m-%d")
[1] NA
> as.Date('2009-02-25', format="%Y-%m-%d")
[1] "2009-02-25"
> as.Date('2009-02-27', format="%Y-%m-%d")
[1] "2009-02-27"
> as.Date('2009-02-28', format="%Y-%m-%d")
[1] "2009-02-28"
> as.Date('2009-02-29', format="%Y-%m-%d")
[1] NA
Additional: I have also tried letting the 'impossible' Date remain as 'NA' and putting it in the right order in a data frame(Right below 28th Feb in this case). But when I turn it into a zoo object, the 'NA date' gets sent to the end of the time series so that didnt work.
Upvotes: 1
Views: 364
Reputation: 263362
Take your choice. I'm pretty sure that zoo can handle ordered character vectors for its index;
> paste(2009, sprintf("%02s",rep(1:12, each=31)), sprintf("%02s", 1:31), sep="-") [55:65]
[1] "2009-02-24" "2009-02-25" "2009-02-26" "2009-02-27" "2009-02-28" "2009-02-29"
[7] "2009-02-30" "2009-02-31" "2009-03-01" "2009-03-02" "2009-03-03"
str (as.Date( paste(year, rep(1:12, each=31), 1:31, sep="-") ) )
Date[1:372], format: "2009-01-01" "2009-01-02" "2009-01-03" "2009-01-04" ...
> as.Date( paste(2009, rep(1:12, each=31), 1:31, sep="-") ) [55:65]
[1] "2009-02-24" "2009-02-25" "2009-02-26" "2009-02-27" "2009-02-28" NA
[7] NA NA "2009-03-01" "2009-03-02" "2009-03-03"
Do note that paste
(like data.frame
) will recycle short vectors which expelains why no rep
is needed for '2009' and why the second rep(.)
is only 31 elements long.
Upvotes: 3