检查数值向量是否包含 na 或字符

Check if numeric vector contains na or character

我有如下输入向量:

x1 <- c('NA', 'NA', 'NA')
x2 <- c(NA, NA, NA)

我想测试(没有循环)这些向量是否包含 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)
*/

但它让我:

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)
  */

输出:

> 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"

请注意,x2 实际上不是数值向量。这些 NA 是逻辑值。如果你想专门测试它,你应该使用 Rf_isLogical(或者 Rf_isIntegerRf_isReal 来识别数字)。