ComenzarEmpieza gratis

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

Ver curso

Instrucciones del ejercicio

  • Completa la definición de la función weighted_mean_cpp().
    • Inicializa total_xw y total_w a cero, y n al tamaño de x.
    • Especifica los argumentos del bucle for, usando un entero i como contador.
    • Dentro del bucle, suma la ponderación i-ésima a total_w y el valor de datos i-ésimo por la ponderación i-ésima a total_xw.
    • Devuelve el producto total dividido por la ponderación total.

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))
*/
Editar y ejecutar código