R using lubridate subtract 6 months but the dates dose not exist?

Advertisements

I want to subtract 6 months from a date but using lubridate I get some NA’s. Here are my attempts:

> as.Date("2013-12-31") - months(6)
[1] NA
> as.Date("2013-12-30") - months(6)
[1] "2013-06-30"
> as.Date("2014-01-01") - months(6)
[1] "2013-07-01"
> as.Date("2012-12-31") - months(6)
[1] NA
> as.Date("2014-12-31") - months(6)
[1] NA
> 

is it because there is no "2013-06-31", June having only 30 days? In which case I might just subtract 366/2 = 183 days.

>Solution :

Use the %m-% operator:

as.Date("2013-12-31") %m-% months(6)
#[1] "2013-06-30"

Leave a ReplyCancel reply