在Rcpp中使用R的“哪个”函数,不返回值

时间:2019-06-12 20:47:50

标签: rcpp

我已经编写了一个Rcpp函数来调用R的哪个函数来检查是否相等。它可以很好地编译,但似乎只返回向量中第一项的值:mywhich(samplevector, samplevector[1])返回一个值,mywhich(samplevector, samplevector[2])返回numeric(0)

该函数的代码如下,它仅需在数值和整数向量上运行

#include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
SEXP mywhich(SEXP x, SEXP y) {

  //For each supported type, turn it into the 'real' type and
  //perform the operation. We can use TYPEOF to check the type.
  switch(TYPEOF(x)){
  case REALSXP: { 
   Environment base("package:base"); 
   Function f("which");
   NumericVector answer = f(as<NumericVector>(y) == as<NumericVector>(x));
   return wrap(answer);
}
  case INTSXP: { 
    Environment base("package:base"); 
    Function f("which");
    IntegerVector answer = f(as<IntegerVector>(y) == as<IntegerVector>(x));
    return wrap(answer);
  }
  default: {
    stop("Only integer and numeric vectors are supported");
  }
  }}

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

在R中执行<long vector> == <short vector>时,短向量将被回收以匹配长向量的长度。在Rcpp中不会发生这种情况!在您的情况下,您想执行<vector> == <single element vector>,可以在Rcpp中使用<vector> == <double/int/...>完成。这意味着您必须从单个元素向量中选择0元素。在您的代码中:

#include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
SEXP mywhich(SEXP x, SEXP y) {

  //For each supported type, turn it into the 'real' type and
  //perform the operation. We can use TYPEOF to check the type.
  switch(TYPEOF(x)){
  case REALSXP: { 
   Environment base("package:base"); 
   Function f("which");
   NumericVector answer = f(as<NumericVector>(y)(0) == as<NumericVector>(x));
   //                                           ^^^
   return wrap(answer);
}
  case INTSXP: { 
    Environment base("package:base"); 
    Function f("which");
    IntegerVector answer = f(as<IntegerVector>(y)(0) == as<IntegerVector>(x));
    //                                           ^^^
    return wrap(answer);
  }
  default: {
    stop("Only integer and numeric vectors are supported");
  }
  }}

顺便说一句,我不认为您需要R中的which来在LogicalVector中找到true的索引。

相关问题