缺失值的处理
在 R 中,判断缺失值必须使用 is.na(x)。(如果尝试 x == NA 会发生什么?)
在 Rcpp 中的等价用法是静态方法 is_na()。请回忆,静态表示该方法属于类本身,而不是某个具体变量。例如,NumericVector::is_na(x) 用于测试 double 类型的 x 是否为缺失值。
类似地,静态方法 get_na() 会给出对应类的 NA。例如,CharacterVector::get_na() 会返回一个缺失的字符值。
请注意,C++ 中的逻辑「或」与 R 相同,写作 ||。
本练习是课程的一部分
用 Rcpp 优化 R 代码
练习说明
- 基于上一个练习,更新
weighted_mean_cpp()函数,使其在x或w中一旦遇到缺失值就立即返回缺失值。- 添加一个
if代码块,检查x的第 i 个元素是否为NA,或w的第 i 个元素是否为NA。 - 在该
if代码块内部,返回一个数值型NA。
- 添加一个
交互式实操练习
通过完成这段示例代码来试试这个练习。
#include
using namespace Rcpp;
// [[Rcpp::export]]
double weighted_mean_cpp(NumericVector x, NumericVector w) {
double total_w = 0;
double total_xw = 0;
int n = x.size();
for(int i = 0; i < n; i++) {
// If the ith element of x or w is NA then return NA
___
total_w += w[i];
total_xw += x[i] * w[i];
}
return total_xw / total_w;
}
/*** R
x <- c(0, 1, 3, 6, 2, 7, 13, NA, 12, 21, 11)
w <- 1 / seq_along(x)
weighted_mean_cpp(x, w)
*/