[英]Calling R function from Rcpp
I have a very basic question about C++ integration in R via Rcpp. 我有一个关于通过Rcpp在R中进行C ++集成的非常基本的问题。 Suppose I want to implement a simple function like this one in C++:
假设我想在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: 因此,一种非常基本的方法是根据需要调用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];
}
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. 但是,我需要在我的C ++代码的许多其他部分中使用此“ intecxx”,因此从其他位置调用它会导致“ inte”在范围内不可用。 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: 如果您愿意通过硬编码
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];
}
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
. 我在与
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.