始める無料で始める

加重平均(C++ 版)

ベクトルの加重平均を計算する関数を作成して、身につけたスキルを実践しましょう。

数値ベクトル x(データ値)と、もう一つの数値ベクトル w(重み)が与えられたとき、加重平均は「各データ値に重みを掛けた総和」を「重みの総和」で割ったものです。xw は同じ要素数である必要があります。

R では weighted.mean() を使い、内部では sum(x * w) / sum(w) が計算されます。

この演習はコースの一部です

Rcpp で R コードを最適化する

コースを見る

演習の手順

  • weighted_mean_cpp() 関数の定義を完成させてください。
    • total_xwtotal_w を 0 に初期化し、n には x のサイズを代入します。
    • for ループの引数を指定し、カウンタには整数の i を使います。
    • ループ内で、i 番目の重みを total_w に、i 番目のデータ値と i 番目の重みの積を total_xw に加算します。
    • 最後に、積の合計を重みの合計で割った値を返します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

#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))
*/
コードを編集して実行