subset a list using time in r

In R, if you have a list of time series data, you can subset that list to include only the data between certain time points. Here is an example of how to do that.

Let's assume you have a list of time series data called ts_list. Each element in the list is a time series object with a start and end time. To subset the list so that we only keep the elements that fall within a certain time period, we can use the lapply() function along with a function that checks the start and end times of each element.

For example, let's say we want to keep all time series elements that begin after January 1, 2010 and end before December 31, 2015. We can create a function to check this as follows:

main.r
check_within_timeperiod <- function(ts_obj) {
  start_date <- as.Date(start(ts_obj))
  end_date <- as.Date(end(ts_obj))
  if (start_date > as.Date("2010-01-01") & end_date < as.Date("2015-12-31")) {
    return(ts_obj)
  }
}
224 chars
8 lines

This function checks if the start date is after January 1, 2010 and if the end date is before December 31, 2015. If both conditions are met, it returns the time series object. Otherwise, it returns NULL.

Next, we can use the lapply() function along with this function to subset our original ts_list:

main.r
new_list <- lapply(ts_list, check_within_timeperiod)
53 chars
2 lines

The resulting new_list will only contain the time series data elements that fall within our desired time period.

related categories

gistlibby LogSnag