Rcpp에서 NA 반환

Nov 14 2020

Rcpp를 통해 NA를 반환하려고합니다. get_na()이 게시물 에서 제안한대로 여기에서 작동하지 않는 이유를 이해할 수 없습니다 .

> Rcpp::cppFunction('NumericVector temp1() {
   return NumericVector::get_na();
 }')
> temp1()
Error in temp1() : negative length vectors are not allowed

내가 시도 create()하면 작동합니다.

> Rcpp::cppFunction('NumericVector temp2() {
    return NumericVector::create(NA_REAL);
  }')
> temp2()
  NA

답변

4 BenjaminChristoffersen Nov 14 2020 at 16:40

다음과 같이해야합니다.

Rcpp::cppFunction('NumericVector temp1() {
  NumericVector y(1);
  y[0] = NumericVector::get_na();
  return y;
}')

temp1()
#R> [1] NA

사용하려는 경우 NumericVector::get_na(). 참고가 이 멤버 함수는 단순히 반환 NA_REAL당신이 presuambly에 오류 얻을 이유입니다 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 반환

그런 다음 벡터 다른 종류의를 처리하는 경우 NumericVectorget_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