0

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"
> 
itthrill
  • 1,241
  • 2
  • 17
  • 36

3 Answers3

3

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+%`

Gabriel M. Silva
  • 642
  • 4
  • 10
2

We can use %m- from lubridate to resolve the issue

library(lubridate)
as.Date(x) %m-% months(6)
# [1] "2017-04-30"
akrun
  • 874,273
  • 37
  • 540
  • 662
1

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"

Hansel Palencia
  • 1,006
  • 9
  • 17