Exercise

Mean carried forward

An alternative to last observation carried forward is to replace NAs with the mean of all the previous non-NA values. This is called mean carried forward. Again, R makes us choose between readability and speed. The following is written for readability:

na_meancf1 <- function(x) {
  total_not_na <- 0
  n_not_na <- 0
  res <- x
  for(i in seq_along(x)) {
    if(is.na(x[i])) {
      res[i] <- total_not_na / n_not_na
    } else {
      total_not_na <- total_not_na + x[i]
      n_not_na <- n_not_na + 1
    }
  }
  res
}

The iterative nature makes this tricky to vectorize, so instead, let's convert it to C++. Complete the definition of na_meancf2(), a C++ translation of na_meancf1().

Instructions

100 XP
  • In the if condition, check if the ith element of x is a NumericVector's NA.
  • If the condition is true, set the ith result to the total of non-missing values, total_not_na, divided by the number of missing values, n_not_na.
  • Otherwise, increase total_not_na by the ith element of x, and add 1 to n_not_na.