2

I have a date, let's say July 7th, 2020.

my_date <- as.Date("2020/07/07")

I want to offset this date by one month. So it should return August 7th, 2020.

I tried my_date + 30 but it doesn't work if the month has 30 or 31 days.

EDIT

I have to be precise in my question. What if the date is May 31, 2020? It should offset to June 30, 2020. Please, a help in base R is desirable.

Any help will be greatly appreciated.

Manu
  • 1,070
  • 10
  • 27

2 Answers2

5

Use %m+% from lubridate

library(lubridate)
my_date <- as.Date("2020/07/07")
my_date %m+% months(1)
#[1] "2020-08-07"

my_date + months(1) also works in this case but it messes up calculation if it's last day of month.

my_date <- as.Date("2020/05/31")
my_date + months(1)
#[1] NA

my_date %m+% months(1)
#[1] "2020-06-30"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Hello @Ronak Shah, I have edited my question due to your concern on a date like May 31. Just a question, do you know if a base R solution is possible in this case? – Manu Jul 08 '20 at 03:05
  • 1
    I am not aware about a flawless and simple approach to do this in base R. I can think of method suggested by Jilber, or using `as.POSIXlt` and changing `mon` part from it Or using some regex. All these methods have their own drawbacks. Perhaps, you can write your own custom function using some `if`/`else` to test for various months if you don't want to use `lubridate` function. – Ronak Shah Jul 08 '20 at 03:29
  • I appreciate your time and answer Ronak, I think it's better to use `lubridate` and code faster. Have a great day! – Manu Jul 08 '20 at 03:58
3

You can use seq

> my_date <- as.Date("2020/07/07")
> seq(my_date,length=2,by="months")[2]
[1] "2020-08-07"
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • 1
    `my_date <- as.Date("2020/05/31")` – Ronak Shah Jul 08 '20 at 02:47
  • Hello @Jilber Urbina, thank you for the answer, but I realized a flaw in my question, what if the date is May 31? I have edited my question above to be more clear. – Manu Jul 08 '20 at 03:07