You can use the following functions from the lubridate package in R to quickly add and subtract months from a date:
Method 1: Add Months
#add two months to date my_date %m+% months(2)
Method 2: Subtract Months
#subtract two months from date my_date %m-% months(2)
The following examples show how to use each method in practice.
Example 1: Add Months to Date
The following code shows how to add two months to a date in R:
library(lubridate) #define date my_date Date("2022-7-15") #add two months to date my_date %m+% months(2) [1] "2022-09-15"
Notice that two months have been added to the original date of 7/15/2022 to produce a new date of 9/15/2022.
Example 2: Subtract Months from Date
The following code shows how to subtract two months from a date in R:
library(lubridate) #define date my_date Date("2022-7-15") #subtract two months from date my_date %m-% months(2) [1] "2022-05-15"
Notice that two months have been subtracted from the original date of 7/15/2022 to produce a new date of 5/15/2022.
Example 3: Add & Subtract Months in Data Frame
Suppose we have the following data frame in R:
#create data frame df frame(date=as.Date(c("2022-3-14", "2022-5-29", "2022-7-15")), sales=c(140, 119, 138)) #view data frame df date sales 1 2022-03-14 140 2 2022-05-29 119 3 2022-07-15 138
We can use the following code to create new columns in the data frame by adding or subtracting months from the original value in the date column:
library(lubridate) #create new column that adds two months to each date df$two_months_after %m+% months(2) #create new column that subtracts two months from each date df$two_months_before %m-% months(2) #view updated data frame df date sales two_months_after two_months_before 1 2022-03-14 140 2022-05-14 2022-01-14 2 2022-05-29 119 2022-07-29 2022-03-29 3 2022-07-15 138 2022-09-15 2022-05-15
Notice that two new columns have been added to the data frame.
Additional Resources
The following tutorials explain how to perform other common operations in R:
How to Extract Year from Date in R
How to Group Data by Month in R (W
How to Calculate Number of Months Between Dates in R