我有输入向量,如:
x1 <- c('NA', 'NA', 'NA')
x2 <- c(NA, NA, NA)
Run Code Online (Sandbox Code Playgroud)
我想测试(没有循环),如果这些向量包含NA值或字符值.
我在尝试:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
if (all(is_na(x)) || (x == NA_STRING))
{
Rcout << "NA";
}
return x * 2;
}
/*** R
x1 <- c('NA','NA','NA')
x2 <- c(NA,NA,NA)
timesTwo(x1)
timesTwo(x2)
*/
Run Code Online (Sandbox Code Playgroud)
但它让我失望:
passing 'const LHS_TYPE {aka const Rcpp::sugar::SingleLogicalResult....discards qualifiers
我知道错误来自于我必须使用x作为字符串向量并访问每个元素x(1) == NA_STRING.
所以,我想让x作为一个数字向量,但检查它是否是一个字符向量,就像在R中:
all(is.character(x)
这应该让你开始:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
CharacterVector testNA(const SEXP x) {
CharacterVector test(1, "other");
if (Rf_isString(x)) test = "character";
if (Rf_isNumeric(x)) {
NumericVector y = x;
if (all(is_na(y))) test = "numeric NAs";
}
return test;
}
/*** R
x1 <- c('NA','NA','NA')
x2 <- c(NA,NA,NA)
x3 <- list(NA)
testNA(x1)
testNA(x2)
testNA(x3)
*/
Run Code Online (Sandbox Code Playgroud)
输出:
> x1 <- c('NA','NA','NA')
> x2 <- c(NA,NA,NA)
> x3 <- list(NA)
> testNA(x1)
[1] "character"
> testNA(x2)
[1] "numeric NAs"
> testNA(x3)
[1] "other"
Run Code Online (Sandbox Code Playgroud)
请注意,x2它实际上不是数字向量.那些NA是逻辑值.您应该使用Rf_isLogical,如果你想测试那些专门(或Rf_isInteger和Rf_isReal识别数字).