ส่งคืน NA จาก Rcpp

Nov 14 2020

ฉันพยายามส่งคืน NA ผ่าน Rcpp ฉันไม่เข้าใจว่าทำไม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ซึ่งเป็นสาเหตุที่ทำให้คุณได้รับข้อผิดพลาดด้วยตัว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;
}')

ส่งคืน NA จาก Rcpp

หากคุณกำลังเผชิญกับประเภทอื่น ๆ ของเวกเตอร์แล้วNumericVectorแล้วget_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