我正在尝试以y
第二个可为空向量 ( r
)的值是否为条件来评估向量 ( )的总和NA
。如果第二个向量r
为 NULL,y
则应将 的所有值相加。如果 的所有元素r
都是NA
,则函数应返回 NA。请参阅文本末尾以获得所需的输出。
我首先尝试了以下代码:
library(Rcpp)
cppFunction('double foo(NumericVector y, Rcpp::Nullable<Rcpp::IntegerVector> r = R_NilValue) {
double output = 0;
bool return_na = !Rf_isNull(r);
int y_count = y.size();
for (int i = 0; i < y_count; i++) {
if (Rf_isNull(r) || !R_IsNA(r[i])) {
//// if (Rf_isNull(r) || !R_IsNA(as<IntegerVector>(r)[i])) {
if (!Rf_isNull(r))
Rcout << R_IsNA(as<IntegerVector>(r)[i]) << " - "<< as<IntegerVector>(r)[i] << std::endl;
output = output + y[i];
return_na = false;
}
}
if (return_na)
return NA_REAL;
return output;
}')
Run Code Online (Sandbox Code Playgroud)
这给了我以下错误:
error: invalid use of incomplete type 'struct SEXPREC'
if (Rf_isNull(r) || !R_IsNA(r[i])) {
^
Run Code Online (Sandbox Code Playgroud)
为了解决它,我if (Rf_isNull(r) || !R_IsNA(as<IntegerVector>(r)[i])) {
改为使用。但是这一次,当转换为整数向量时,NA
值被转换为数字并且R_IsNA()
test 给出了误报。
这是我想要的预期输出。
foo(1:4, NULL) # <- This should return 10 = 1 + 2 + 3 + 4
foo(1:4, c(1, 1, 1, 1)) # <- This should return 10 = 1 + 2 + 3 + 4
foo(1:4, c(1, 1, NA, 1)) # <- This should return 7 = 1 + 2 + 4
foo(1:4, c(NA, NA, NA, NA)) # <- This should return NA
Run Code Online (Sandbox Code Playgroud)
我怎样才能得到我想要的功能?(这个例子是简化的,我对 sum 函数不是特别感兴趣。相反,我对检查NA
和NULL
同时给出的例子感兴趣。)
三点建议:
r
的NULL
。LogicalVector
before 循环输入向量。#include <Rcpp.h>
// [[Rcpp::export]]
double foo(Rcpp::NumericVector y, Rcpp::Nullable<Rcpp::IntegerVector> r = R_NilValue) {
if (r.isNull())
return Rcpp::sum(y);
Rcpp::LogicalVector mask = Rcpp::is_na(r.as());
if (Rcpp::is_true(Rcpp::all(mask)))
return NA_REAL;
double output = 0.0;
int y_count = y.size();
for (int i = 0; i < y_count; ++i) {
if (!mask[i]) {
output += y[i];
}
}
return output;
}
/***R
foo(1:4, NULL) # <- This should return 10 = 1 + 2 + 3 + 4
foo(1:4, c(1, 1, 1, 1)) # <- This should return 10 = 1 + 2 + 3 + 4
foo(1:4, c(1, 1, NA, 1)) # <- This should return 7 = 1 + 2 + 4
foo(1:4, c(NA, NA, NA, NA)) # <- This should return NA
*/
Run Code Online (Sandbox Code Playgroud)
结果:
> Rcpp::sourceCpp('60569482.cpp')
> foo(1:4, NULL) # <- This should return 10 = 1 + 2 + 3 + 4
[1] 10
> foo(1:4, c(1, 1, 1, 1)) # <- This should return 10 = 1 + 2 + 3 + 4
[1] 10
> foo(1:4, c(1, 1, NA, 1)) # <- This should return 7 = 1 + 2 + 4
[1] 7
> foo(1:4, c(NA, NA, NA, NA)) # <- This should return NA
[1] NA
Run Code Online (Sandbox Code Playgroud)
进一步建议:
y
。> Rcpp::sourceCpp('60569482.cpp')
> foo(1:4, NULL) # <- This should return 10 = 1 + 2 + 3 + 4
[1] 10
> foo(1:4, c(1, 1, 1, 1)) # <- This should return 10 = 1 + 2 + 3 + 4
[1] 10
> foo(1:4, c(1, 1, NA, 1)) # <- This should return 7 = 1 + 2 + 4
[1] 7
> foo(1:4, c(NA, NA, NA, NA)) # <- This should return NA
[1] NA
Run Code Online (Sandbox Code Playgroud)