简体   繁体   中英

Calling R function from Rcpp

I have a very basic question about C++ integration in R via Rcpp. Suppose I want to implement a simple function like this one in C++:

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

So a very basic approach would be to call R's function 'integrate' as much as needed:

// [[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];
}

However, I need to use this 'intecxx' in many other parts of my C++ code, so calling it from somewhere else results in 'inte' not being available in the scope. Any help is appreciated.

If you are willing to modify intecxx by hardcoding the call to inte inside the body, rather than trying to pass it as a parameter, you could use this approach:

#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];
}

I defined inte in the same source file as intecxx to ensure that it is available in the global environment, and therefore callable from within intecxx through 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM