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).
Cet exercice fait partie du cours
Optimizing R Code with Rcpp
Instructions
- Complete the definition of the
weighted_mean_cpp()function.- Initialize
total_xwandtotal_wto zero, andnto the size ofx. - Specify the arguments to the
forloop, with an integer,ias the counter. - Inside the loop, add the ith weight to
total_wand the ith data value times the ith weight tototal_xw. - Return the total product divided by the total weight.
- Initialize
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
#include
using namespace Rcpp;
// [[Rcpp::export]]
double weighted_mean_cpp(NumericVector x, NumericVector w) {
// Initialize these to zero
double total_w = ___;
double total_xw = ___;
// Set n to the size of x
int n = ___;
// Specify the for loop arguments
for(int i = 0; ___) {
// Add ith weight
total_w += ___;
// Add the ith data value times the ith weight
total_xw ___;
}
// Return the total product divided by the total weight
return ___;
}
/*** R
x <- c(0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11)
w <- 1 / seq_along(x)
weighted_mean_cpp(x, w)
# Does the function give the same results as R's weighted.mean() function?
all.equal(weighted_mean_cpp(x, w), weighted.mean(x, w))
*/