Session Ready
Exercise

Last observation carried forward

When you have missing data in a time series, one common technique is to carry forward the last value that wasn't missing. This is known as the last observation carried forward. It can naturally be expressed with iterative code. Here's an implementation using R:

na_locf1 <- function(x) {
  current <- NA  
  res <- x
  for(i in seq_along(x)) {
    if(is.na(x[i])) {
      # Replace with current
      res[i] <- current
    } else {
      # Set current 
      current <- x[i]
    }
  }  
  res
}

Like rolling means, it's really difficult to vectorize this code while keeping it readable. However, since this is just a for loop, it can be easily translated to C++.

na_locf1() is provided in your workspace. Convert it to C++ and assign it to na_locf2().

Instructions
100 XP
  • Initialize current to the NumericVector's NA value.
  • The if condition should check if the ith element of x is a NumericVector's NA.
  • When that condition is true, set the ith element of res to current.
  • Otherwise, set current to the ith element of x.