Skip to content

Instantly share code, notes, and snippets.

@ateucher
Last active August 19, 2019 07:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ateucher/e2e5bd0b592f3efd6d56 to your computer and use it in GitHub Desktop.
Save ateucher/e2e5bd0b592f3efd6d56 to your computer and use it in GitHub Desktop.
Filling in missing dates in a time series data frame
## First make up some mock data
my_data <- data.frame(date = seq(as.Date("2010-01-01"), as.Date("2015-12-31"),
by = "1 month"),
value = rnorm(72))
## Remove some observations so we have an incomplete data set
my_incomplete_data <- my_data[sort(sample(nrow(my_data), 60)), ]
## Make a data frame with a full series of dates from the min date to the max date
## in the incomplete data frame
full_dates <- seq(min(my_incomplete_data$date), max(my_incomplete_data$date),
by = "1 month")
full_dates <- data.frame(date = full_dates)
## Merge the complete data frame with the incomplete to fill in the dates and add
## NAs for missing values
my_complete_data <- merge(full_dates, my_incomplete_data, by = "date",
all.x = TRUE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment