Media ponderada (versión en C++)
Es hora de poner en práctica lo aprendido creando una función que calcule la media ponderada de un vector.
Dado un vector numérico de valores, x, y otro vector numérico de ponderaciones, w, la media ponderada es la suma de cada valor multiplicado por su ponderación dividida por la suma de las ponderaciones. Ten en cuenta que x y w deben tener el mismo número de elementos.
En R se calcula con weighted.mean(), que hace sum(x * w) / sum(w).
Este ejercicio forma parte del curso
Optimizar código de R con Rcpp
Instrucciones del ejercicio
- Completa la definición de la función
weighted_mean_cpp().- Inicializa
total_xwytotal_wa cero, ynal tamaño dex. - Especifica los argumentos del bucle
for, usando un enteroicomo contador. - Dentro del bucle, suma la ponderación i-ésima a
total_wy el valor de datos i-ésimo por la ponderación i-ésima atotal_xw. - Devuelve el producto total dividido por la ponderación total.
- Inicializa
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
#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))
*/