Get startedGet started for free

Handling of missing values

In R, to test for a missing value you must use is.na(x). (What happens if you try x == NA?)

The equivalent in Rcpp is the static method is_na(). Recall that static means the method is part of the class, not the particular variable. For example, NumericVector::is_na(x) tests if the double x is a missing value.
Similarly, the static method get_na() gives you the NA for the associated class. For example, CharacterVector::get_na() returns a missing character value.

Note that the logical or in C++ is the same as in R, ||.

This exercise is part of the course

Optimizing R Code with Rcpp

View Course

Exercise instructions

  • Update the weighted_mean_cpp() function from the previous exercise so that it returns a missing value as soon as a missing value is seen on x or w.
    • Add an if block that checks if the ith element of x is NA or the ith element of w is NA.
    • Inside that if block, return a numeric NA.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

#include 
using namespace Rcpp;

// [[Rcpp::export]]
double weighted_mean_cpp(NumericVector x, NumericVector w) {
  double total_w = 0;
  double total_xw = 0;
  
  int n = x.size();
  
  for(int i = 0; i < n; i++) {
    // If the ith element of x or w is NA then return NA
    ___
    
    
    total_w += w[i];
    total_xw += x[i] * w[i];
  }
  
  return total_xw / total_w;
}

/*** R 
x <- c(0, 1, 3, 6, 2, 7, 13, NA, 12, 21, 11)
w <- 1 / seq_along(x)
weighted_mean_cpp(x, w)
*/
Edit and Run Code