问题描述
我有一个带有一堆用户定义的 R 函数的 R 代码.我试图让代码运行得更快,当然最好的选择是使用 Rcpp.我的代码涉及相互调用的函数.因此,如果我用 C++ 编写一些函数,我应该能够在我的 C++ 代码中调用和运行我的一些 R 函数.在一个简单的例子中,考虑下面的 R 代码:
I have an R code with a bunch of user-defined R functions. I'm trying to make the code run faster and of course the best option is to use 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. In a simple example consider the code below in R:
mySum <- function(x, y){
return(2*x + 3*y)
}
x <<- 1
y <<- 1
现在考虑我试图访问上述函数的 C++ 代码:
Now consider the C++ code in which I'm trying to access the function above:
#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)));
}
当我使用内联函数 sourceCpp() 在 R 中获取文件时,出现错误:
When I source the file in R with the inline function sourceCpp(), I get the error:
"invalid conversion from 'SEXPREC*' to int
谁能帮我调试代码?我的代码有效吗?可以概括吗?使用 mySum 函数有什么比我在代码中所做的更好的主意吗?
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?
非常感谢您的帮助.
推荐答案
你声明函数应该返回一个 int
,但是使用 wrap
表示返回的对象应该成为 SEXP
.此外,从 Rcpp
(通过 Function
)调用 R 函数也会返回一个 SEXP
.
You declare that the function should return an int
, but use wrap
which indicates the object returned should be a SEXP
. Moreover, calling an R function from Rcpp
(through Function
) also returns a SEXP
.
你想要这样的东西:
#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));
}
(或者,将函数返回保留为 int
并使用 as
代替 wrap
).
(or, leave function return as int
and use as<int>
in place of wrap
).
也就是说,这是一种非惯用的 Rcpp
代码.请记住,从 C++ 调用 R 函数仍然会很慢.
That said, this is kind of non-idiomatic Rcpp
code. Remember that calling R functions from C++ is still going to be slow.
这篇关于使用 Rcpp 从 C++ 调用用户定义的 R 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!