【问题标题】:Rcpp: Converting SEXP to float/doubleRcpp:将 SEXP 转换为浮点数/双精度数
【发布时间】:2018-08-09 21:40:19
【问题描述】:
SEXP callFunction1(List network, List words, Function testWordContinuity){
  SEXP res = testWordContinuity(network, words);
  return res;
}

for(int i=0; i<(n_epochs); i++){
  NumericVector outputMatchTracker = history["output.match.tracker"];
  outputMatchTracker[i] = callFunction1(network, words, testWordContinuity);
}

R 中的 testWordContinuity 函数调用 R 中的另一个函数,该函数返回单个数值变量

我对 res 所做的只是使用 for 循环替换向量中的值。 for 循环开始后的第一行是将 outputMatchTracker 分配给一个零向量 (history["output.match.tracker"]),这样我就可以遍历零。

错误:“Cannot convert 'SEXP' to 'Rcpp::traits::storage_type::type {aka double}' in assignment”出现在上面 for 循环的最后一行。

有没有办法将 res 从 SEXP 转换为 float 或 double?

我意识到这里有人问过类似的问题: Rcpp cannot convert ‘SEXP {aka SEXPREC*}’ to ‘double’ in initialization 但这个问题是通过使用 Rcpp 糖函数而不是 R 函数来解决的,以避免将 SEXP 转换为双精度。

如果没有办法从 SEXP 转换为浮点数或双精度数,除了在 Rcpp 中编写 R 函数之外,是否有解决此问题的常用方法?

如有必要,很乐意提供更多信息,

谢谢。

编辑:

最小可重现示例:

在 Rcpp 中:

// [[Rcpp::export]]
SEXP callFunction(Function func){
  SEXP res = func();
  return(res);
}

// [[Rcpp::export]]
NumericVector func1(Function func){
  for(int i=0; i<10; i++){
    NumericVector vect(10);
    vect[i] = callFunction(func);
  }
  return(vect);
}

获取此代码后,将出现上面指定的错误。

【问题讨论】:

  • 欢迎来到 StackOverflow!您的问题中有很多废话,但没有minimal reproducible example,因此我们只能说很少。请编辑以提供触发错误的最小但完整的内容。
  • 你试过as&lt;&gt;操作符吗? @DirkEddelbuettel 撰写了一篇对这类事情非常透彻的文章。可以找到here
  • Psst @JosephWood Dirk 撰写了许多精彩的 Rcpp 文章;但是,我写了一个:)
  • @coatless,我觉得自己像个白痴。那是超级粗心和无意的。我每天都在Rcpp Galary,发现那篇文章很快,复制链接,甚至懒得看作者。我非常抱歉。我非常尊重您,并经常宣传您​​的工作和网站。
  • as 运算符成功了。我之前曾尝试过,但显然语法不正确。谢谢!

标签: r floating-point type-conversion double rcpp


【解决方案1】:

我相信你应该使用REAL 宏,它返回一个指向double 数组开头的指针。示例见https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Attributes

【讨论】:

  • 在 Rcpp 世界中不需要。 cppFunction("double plusTwo(double x) { return x + 2.0; }")Rcpp::NumericVector 同上,如果您想要一个向量而不是 (C/C++) 标量。
【解决方案2】:

作为Simon Byrne's answer 的扩展 - 我知道有两种方法可以实现这一点:

  1. 请记住,R 中的标量实际上始终是长度为 1 的向量。因此,将 R SEXP 对象转换为 RCPP NumericVector 并使用索引(方括号)表示法来引用第一个元素:
double callFunction1(List network, List words, Function testWordContinuity){
  SEXP res = testWordContinuity(network, words);
  NumericVector dblVec(res)
  return dblVec[0];
}
  1. 使用REAL 宏并取消引用指针(指向第一个元素)。与方法 1(未经测试)相比,这很可能是一个微优化,但瓶颈几乎肯定是 testWordContinuity R 函数。在&lt;Rinternals.h&gt; C 库中还有一个asReal 函数,但鉴于REAL 宏包含在&lt;Rcpp.h&gt; 头文件中,它似乎增加了不必要的复杂性来打扰包括&lt;Rinternals.h&gt;
double callFunction1(List network, List words, Function testWordContinuity){
  SEXP res = testWordContinuity(network, words);
  return *REAL(res);
}

【讨论】:

    猜你喜欢
    • 2015-06-12
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 2011-11-22
    • 2014-01-30
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    相关资源
    最近更新 更多