Session Ready
Exercise

Fill missing values using last or previous observation

As you've encountered already, it's not uncommon to find yourself with missing values (i.e. NAs) in your time series. This may be the result of a data omission or some mathematical or merge operation you do on your data.

The xts package leverages the power of zoo for help with this. zoo provides a variety of missing data handling functions which are usable by xts.

In this exercise you will use the most basic of these, na.locf(). This function takes the last observation carried forward approach. In most circumstances this is the correct thing to do. It both preserves the last known value and prevents any look-ahead bias from entering into the data.

You can also apply next observation carried backward by setting fromLast = TRUE.

# Last obs. carried forward
na.locf(x)                

# Next obs. carried backward
na.locf(x, fromLast = TRUE) 
Instructions
100 XP
  • Using a subset of temps, fill missing NA observations with the last observation known. Store them in temps_last.
  • Using another subset of temps, backfill missing NA observations with the next observation. Store them in temps_next.