Session Ready
Exercise

Weighted mean (C++ version)

Time to put your skills into action by creating a function to calculate the weighted mean of a vector.

Given a numeric vector of data values, x, and another numeric vector of weights, w, the weighted mean is the sum of the data value times the weights divided by the sum of the weights. Note that x and w should have the same number of elements.

In R, it is calculated with weighted.mean(), which does sum(x * w) / sum(w).

Instructions
100 XP
  • Complete the definition of the weighted_mean_cpp() function.
    • Initialize total_xw and total_w to zero, and n to the size of x.
    • Specify the arguments to the for loop, with an integer, i as the counter.
    • Inside the loop, add the ith weight to total_w and the ith data value times the ith weight to total_xw.
    • Return the total product divided by the total weight.