Insert Rows for Missing Dates in R (Example)
In this post you’ll learn how to add new rows in case a date is missing in R.
The tutorial will contain one example for the addition of new rows. More precisely, the post will consist of the following:
Let’s dig in!
Creation of Example Data
Have a look at the following example data:
data <- data.frame(date = as.Date(c("2022-10-01", # Create example data "2022-10-03", "2022-10-06", "2022-10-07")), values = 10:13) data # Print example data
As you can see based on Table 1, the example data is a data frame and is constructed of four rows and two columns.
The first column contains some dates and the second column consists of numeric values.
Note that the date column is formatted as a real date, since we have used the as.Date function within the data creation process. If your date column is a character string instead, you have to convert this character string to the Date class.
As you can see, some of the dates in between are missing, i.e. the date range is not complete. The following example explains how to insert new rows for these missing dates.
Example: Insert Empty Rows for Missing Dates Using pad() Function of padr Package
In this example, I’ll explain how to use the padr package to insert a new row for each missing day in our date range.
We first need to install and load the padr add-on package.
install.packages("padr") # Install & load padr package library("padr")
Next, we can use the pad function of the padr package to insert empty rows for each missing date in our range:
data_new <- pad(data) # Applying pad function data_new # Print updated data
After executing the previously shown syntax the data frame data_new revealed in Table 2 has been created.
As you can see, this new data frame contains empty rows for each missing date.
Video, Further Resources & Summary
Would you like to know more about dates and times in R? Then you might want to watch the following video that I have published on my YouTube channel. I’m explaining the topics of this tutorial in the video.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you may have a look at the other articles on this website:
- How to Split a Date-Time Column into Separate Variables
- Convert Dates to Year/Quarter Format in R
- Remove Rows with NA in R Data Frame
- R Programming Overview
This tutorial has illustrated how to insert new rows in case a date is missing in a data frame in the R programming language. If you have additional comments and/or questions, let me know in the comments.
Statistics Globe Newsletter