Ritorno NA da Rcpp

Nov 14 2020

Sto cercando di restituire NA tramite Rcpp. Non capisco perché get_na()non funziona qui come suggerito in questo post ?

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

Se provo create()funziona.

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

Risposte

4 BenjaminChristoffersen Nov 14 2020 at 16:40

Devi fare qualcosa come:

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

temp1()
#R> [1] NA

se vuoi usare NumericVector::get_na(). Nota che questa funzione membro restituisce semplicemente, NA_REALmotivo per cui presumibilmente ottieni l'errore con NumericVectoril costruttore di con:

Rcpp::cppFunction('NumericVector temp1() {
   return NumericVector::get_na();
 }')

Puoi altrettanto bene usare NumericVector::createcome suggerisci. Puoi anche fare:

Rcpp::cppFunction('NumericVector temp2() {
  return NumericVector(1, NA_REAL);
}')

o

Rcpp::cppFunction('double temp3() {
  return NA_REAL;
}')

Ritorno NA da Rcpp

Se hai a che fare con altri tipi di vettori, NumericVectorallora la get_nafunzione può essere molto utile. Ecco un esempio in cui restituiamo NA ma con tipi diversi a seconda dell'input.

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