Skip to content

Instantly share code, notes, and snippets.

@thisisnic
Last active November 23, 2018 15:18
Show Gist options
  • Save thisisnic/097c1cc860f302fdb007f83424a49e23 to your computer and use it in GitHub Desktop.
Save thisisnic/097c1cc860f302fdb007f83424a49e23 to your computer and use it in GitHub Desktop.
A favourite overlooked tidyverse function of mine is %m+% from #lubridate which allows you to do maths with dates, whilst accounting for the fact that time periods are not uniform (not all years have 365 days, months differ in length etc).

Adding a month on with a '+' is fairly straightforward.

Code:

library(lubridate)
ymd("2018-01-01") + months(1)

Output:

[1] "2018-02-01"

Using %m+% doesn't appear to be doing any different in this case.

Code:

ymd("2018-01-01") %m+% months(1)

Output:

[1] "2018-02-01"

However in this example, we fail to add a month on as there is no 31st of February.

Code:

ymd("2018-01-31") + months(1)

Output:

[1] NA

Therefore, we need to use the %m+% operator instead.

Code:

ymd("2018-01-31") %m+% months(1)

Output:

[1] "2018-02-28"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment