As shown below I am trying to understand why it is NA in one case and not in another.
> x<-"2017-10-31"
> as.Date(x) - months(6)
[1] NA
> x<-"2018-07-31"
> as.Date(x) - months(6)
[1] "2018-01-31"
>
As shown below I am trying to understand why it is NA in one case and not in another.
> x<-"2017-10-31"
> as.Date(x) - months(6)
[1] NA
> x<-"2018-07-31"
> as.Date(x) - months(6)
[1] "2018-01-31"
>
That is because as.Date("2017-10-31") - months(6)
(exactly) would be 2017-04-31, which doesn't exist.
If you want to subtract months without worrying about exceeding the last day of the month (moon calendar now!), use the fantastic functions %m+%
and %m-%
from lubridate
package.
as.Date("2017-10-31") %m-% months(6)
[1] "2017-04-30"
For more details, ?lubridate::`%m+%`
We can use %m-
from lubridate
to resolve the issue
library(lubridate)
as.Date(x) %m-% months(6)
# [1] "2017-04-30"
Since there are only 30 days in April when you attempt to subtract 6 months from October 31st. It returns NA
.
> x <- "2017-10-31"
> as.Date(x) - months(6)
[1] NA
> x <- "2017-10-30"
> as.Date(x) - months(6)
[1] "2017-04-30"