您需要执行以下操作:
Rcpp::cppFunction('NumericVector temp1() {
NumericVector y(1);
y[0] = NumericVector::get_na();
return y;
}')
temp1()
#R> [1] NA
如果你想使用NumericVector::get_na()。请注意,this member function 只是返回 NA_REAL,这就是为什么您可能会在 NumericVector 的构造函数中遇到错误:
Rcpp::cppFunction('NumericVector temp1() {
return NumericVector::get_na();
}')
您同样可以按照您的建议使用NumericVector::create。你也可以这样做:
Rcpp::cppFunction('NumericVector temp2() {
return NumericVector(1, NA_REAL);
}')
或
Rcpp::cppFunction('double temp3() {
return NA_REAL;
}')
从 Rcpp 返回 NA
如果您正在处理其他类型的向量,那么NumericVector 和get_na 函数会非常有用。这是一个示例,其中我们返回 NA,但根据输入具有不同的类型。
Rcpp::sourceCpp(code = '
#include "Rcpp.h"
using namespace Rcpp;
template<int T>
Vector<T> get_na_genric(){
return Vector<T>(1, Vector<T>::get_na());
}
// [[Rcpp::export]]
SEXP get_nan_vec(SEXP x) {
switch (TYPEOF(x)) {
case INTSXP : return get_na_genric<INTSXP >();
case LGLSXP : return get_na_genric<LGLSXP >();
case REALSXP: return get_na_genric<REALSXP>();
case STRSXP : return get_na_genric<STRSXP >();
case VECSXP : return get_na_genric<VECSXP >();
stop("type not implemented");
}
return get_na_genric<REALSXP>();
}')
for(x in list(integer(), logical(), numeric(), character(),
list())){
out <- get_nan_vec(x)
cat("got:\n")
print(out)
cat("with type ", typeof(out), "\n")
}
#R> got:
#R> [1] NA
#R> with type integer
#R> got:
#R> [1] NA
#R> with type logical
#R> got:
#R> [1] NA
#R> with type double
#R> got:
#R> [1] NA
#R> with type character
#R> got:
#R> [[1]]
#R> NULL
#R>
#R> with type list