Add & Subtract Days to & from Date in R (2 Examples)

 

In this tutorial, I’ll explain how to add or subtract a certain number of days from a date object in the R programming language.

The article looks as follows:

You’re here for the answer, so let’s get straight to the examples:

 

Creation of Example Data

The following data will be used as basement for this R programming tutorial:

my_date <- "2021-10-05"            # Create example date
my_date                            # Print example date
# [1] "2021-10-05"

As you can see based on the previous output of the RStudio console, our example data contains a single date formatted as a character string.

Let’s check the class of our date:

class(my_date)                     # Check class of date
# [1] "character"

Our example date has the character class.

In order to add or subtract values from our date, we have to convert our date to the Date class first:

my_date_new <- as.Date(my_date)    # Convert character to Date
my_date_new                        # Print updated date
# [1] "2021-10-05"

Let’s check the class of our new data object:

class(my_date_new)                 # Class of updated date
# [1] "Date"

Our new data object has the class Date.

 

Example 1: Add Number to Date Object

This example explains how to add a certain number of days to our date object.

For this, we can simply use the + sign as shown below:

my_date_new + 100                  # Add to date
# [1] "2022-01-13"

As you can see, we have added 100 days to our date object.

 

Example 2: Subtract Number from Date Object

Similar to Example 1, we can subtract days from our date using the – sign:

my_date_new - 100                  # Subtract from date
# [1] "2021-06-27"

The previous R code has subtracted 100 days from our date.

 

Video & Further Resources

In case you need further explanations on the R programming codes of this article, you may want to watch the following video of my YouTube channel. I illustrate the contents of this tutorial in the video:

 

The YouTube video will be added soon.

 

In addition, you may have a look at the other articles on this homepage. I have released several articles already.

 

In this R tutorial you learned how to add or subtract days from dates. In case you have further questions, don’t hesitate to let me know in the comments. Besides that, please subscribe to my email newsletter in order to get updates on new tutorials.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


4 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top