加权平均数(C++ 版本)
现在来动手实现一个函数,计算向量的加权平均数。
给定一个数值向量 x(数据值)和另一个数值向量 w(权重),加权平均数等于数据值与权重的乘积之和,除以权重之和。请注意:x 与 w 的元素个数应当相同。
在 R 中,可用 weighted.mean() 计算,其等价于 sum(x * w) / sum(w)。
本练习是课程的一部分
用 Rcpp 优化 R 代码
练习说明
- 完成
weighted_mean_cpp()函数的定义。- 将
total_xw和total_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))
*/