Trả lại NA từ Rcpp

Nov 14 2020

Tôi đang cố gắng trả lại NA thông qua Rcpp. Tôi không hiểu tại sao get_na()không hoạt động ở đây như đề xuất trong bài đăng này ?

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

Nếu tôi thử create()nó hoạt động.

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

Trả lời

4 BenjaminChristoffersen Nov 14 2020 at 16:40

Bạn cần thực hiện một số việc như:

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

temp1()
#R> [1] NA

nếu bạn muốn sử dụng NumericVector::get_na(). Lưu ý rằng hàm thành viên này chỉ trả về NA_REAL, đó là lý do tại sao bạn có thể đoán được lỗi với hàm tạo NumericVectorcủa 's với:

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

Bạn cũng có thể sử dụng NumericVector::createnhư bạn đề xuất. Bạn cũng có thể làm:

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

hoặc là

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

Trả lại NA từ Rcpp

Nếu bạn đang đối phó với các loại vector thì NumericVectorsau đó các get_nachức năng có thể rất hữu ích. Đây là một ví dụ mà chúng tôi trả về NA nhưng với các kiểu khác nhau tùy thuộc vào đầu vào.

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