# How to Add and Subtract Months from a Date in R

You can use the following functions from the lubridate package in R to quickly add and subtract months from a date:

```#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 <- as.Date("2022-7-15")

my_date %m+% months(2)

 "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 <- as.Date("2022-7-15")

#subtract two months from date
my_date %m-% months(2)

 "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 <- data.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 <- df\$date %m+% months(2)

#create new column that subtracts two months from each date
df\$two_months_before <- df\$date %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.