【问题标题】:Calling R function from Rcpp从 Rcpp 调用 R 函数
【发布时间】:2015-04-06 00:16:22
【问题描述】:

我有一个关于通过 Rcpp 在 R 中集成 C++ 的非常基本的问题。假设我想在 C++ 中实现一个像这样的简单函数:

inte = function(x, y, a, b){
   model = approxfun(x, y)
   return(integrate(model, a, b)$value)
}

所以一个非常基本的方法是尽可能多地调用 R 的函数“集成”:

// [[Rcpp::export]]
double intecxx(Function inte, NumericVector x, NumericVector y,
  double a, double b) {  
    NumericVector res;
    res = inte(x, y, a, b);
    return res[0];
}

但是,我需要在我的 C++ 代码的许多其他部分中使用这个“intecxx”,因此从其他地方调用它会导致“inte”在范围内不可用。任何帮助表示赞赏。

【问题讨论】:

标签: r rcpp


【解决方案1】:

如果您愿意通过在正文中硬编码对inte 的调用来修改intecxx,而不是尝试将其作为参数传递,您可以使用以下方法:

#include <Rcpp.h>

/*** R
inte = function(x, y, a, b){
   model = approxfun(x, y)
   return(integrate(model, a, b)$value)
}

.x <- 1:10
set.seed(123)
.y <- rnorm(10)
*/

// [[Rcpp::export]]
double intecxx(Rcpp::NumericVector x, Rcpp::NumericVector y, double a, double b) {  
    Rcpp::NumericVector res;
    Rcpp::Environment G = Rcpp::Environment::global_env();
    Rcpp::Function inte = G["inte"];
    res = inte(x, y, a, b);
    return res[0];
}

我在与intecxx 相同的源文件中定义了inte,以确保它在全局环境中可用,因此可以从intecxx 到G 中调用。

R> inte(.x, .y, 1, 10)
[1] 1.249325

R> intecxx(.x, .y, 1, 10)
[1] 1.249325

R> all.equal(inte(.x, .y, 1, 10),intecxx(.x, .y, 1, 10))
[1] TRUE

【讨论】:

  • 太棒了。荣誉。
猜你喜欢
  • 1970-01-01
  • 2014-06-25
  • 1970-01-01
  • 2019-01-17
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
相关资源
最近更新 更多