简体   繁体   English

使用Rcpp从C ++调用用户定义的R函数

[英]calling a user-defined R function from C++ using Rcpp

I have an R code with a bunch of user-defined R functions. 我有一个带有一堆用户定义的R函数的R代码。 I'm trying to make the code run faster and of course the best option is to use Rcpp. 我试图让代码运行得更快,当然最好的选择是使用Rcpp。 My code involves functions that call each other. 我的代码涉及相互调用的函数。 Therefore, If I write some functions in C++, I should be able to call and to run some of my R functions in my c++ code. 因此,如果我用C ++编写一些函数,我应该能够在我的c ++代码中调用并运行一些R函数。 In a simple example consider the code below in R: 在一个简单的例子中,考虑R中的以下代码:

mySum <- function(x, y){
 return(2*x + 3*y)
}
x <<- 1
y <<- 1

Now consider the C++ code in which I'm trying to access the function above: 现在考虑我正在尝试访问上述函数的C ++代码:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int mySuminC(){
 Environment myEnv = Environment::global_env();
 Function mySum = myEnv["mySum"];
 int x = myEnv["x"];
 int y = myEnv["y"];
 return wrap(mySum(Rcpp::Named("x", x), Rcpp::Named("y", y)));
 }

When I source the file in R with the inline function sourceCpp(), I get the error: 当我使用内联函数sourceCpp()在R中源文件时,我收到错误:

 "invalid conversion from 'SEXPREC*' to int

Could anyone help me on debugging the code? 任何人都可以帮我调试代码吗? Is my code efficient? 我的代码有效吗? Can it be summarized? 可以归纳一下吗? Is there any better idea to use mySum function than what I did in my code? 使用mySum函数比我在代码中做的更好吗?

Thanks very much for your help. 非常感谢您的帮助。

You declare that the function should return an int , but use wrap which indicates the object returned should be a SEXP . 您声明该函数应该返回一个int ,但是使用wrap表示返回的对象应该是SEXP Moreover, calling an R function from Rcpp (through Function ) also returns a SEXP . 此外,从Rcpp (通过Function )调用R函数也会返回SEXP

You want something like: 你想要的东西:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
SEXP mySuminC(){
  Environment myEnv = Environment::global_env();
  Function mySum = myEnv["mySum"];
  int x = myEnv["x"];
  int y = myEnv["y"];
  return mySum(Rcpp::Named("x", x), Rcpp::Named("y", y));
}

(or, leave function return as int and use as<int> in place of wrap ). (或者,将函数返回为int并使用as<int>代替wrap )。

That said, this is kind of non-idiomatic Rcpp code. 也就是说,这是一种非惯用的Rcpp代码。 Remember that calling R functions from C++ is still going to be slow. 请记住,从C ++调用R函数仍然会很慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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