Rcpp + inline - 创建和调用附加函数 [英] Rcpp + inline - creating and calling additional functions
问题描述
我想知道是否可以使用 main 函数中的 inline
包来创建 Rcpp
函数.这是我想要做的一个例子:
I would like to know if there is a way to create Rcpp
functions using the inline
packages within the main function. This is an example of what I want to do:
library(inline)
library(Rcpp)
a = 1:10
cpp.fun = cxxfunction(signature(data1="numeric"),
plugin="Rcpp",
body="
int fun1( int a1)
{int b1 = a1;
b1 = b1*b1;
return(b1);
}
NumericVector fun_data = data1;
int n = data1.size();
for(i=0;i<n;i++){
fun_data[i] = fun1(fun_data[i]);
}
return(fun_data);
")
这应该导致:
> cpp.fun(a)
[1] 1 4 9 16 25 36 49 64 81 100
但是我知道编译器不会接受在 main 方法中创建您自己的函数.我将如何使用 inline
创建和调用另一个 Rcpp
函数而不必将其传递给 R?
however I know that the compiler will not accept the creation of your own function within the main method. How will I go about creating and calling another Rcpp
function with inline
without having to pass it through to R?
推荐答案
body
是针对函数体的,要查看includes
参数的<代码>cxx函数:
body
is for the body of the function, you want to look at the includes
argument of cxxfunction
:
library(inline)
library(Rcpp)
a = 1:10
cpp.fun = cxxfunction(signature(data1="numeric"),
plugin="Rcpp",
body='
IntegerVector fun_data = data1;
int n = fun_data.size();
for(int i=0;i<n;i++){
fun_data[i] = fun1(fun_data[i]);
}
return(fun_data);
', includes = '
int fun1( int a1){
int b1 = a1;
b1 = b1*b1;
return(b1);
}
' )
cpp.fun( a )
?cxxfunction
有关于它的 includes
参数的详细文档.
?cxxfunction
has detailed documentation about its includes
argument.
但请注意,此版本将在您的输入向量中进行适当的修改,这可能不是您想要的.另一个同样利用 Rcpp
版本的 sapply
的版本:
But note that this version will make in place modifications in your input vector, which is probably not what you want. Another version that also takes advantage of Rcpp
version of sapply
:
library(inline)
library(Rcpp)
a = 1:10
cpp.fun = cxxfunction(signature(data1="numeric"),
plugin="Rcpp",
body='
IntegerVector fun_data = data1;
IntegerVector out = sapply( fun_data, fun1 ) ;
return(out);
', includes = '
int fun1( int a1){
int b1 = a1;
b1 = b1*b1;
return(b1);
}
' )
cpp.fun( a )
a
最后,您绝对应该看看 sourceCpp
.有了它,您可以在 .cpp
文件中编写代码,其中包含:
Finally, you definitely should have a look at sourceCpp
. With it you would write your code in a .cpp
file, containing:
#include <Rcpp.h>
using namespace Rcpp ;
int fun1( int a1){
int b1 = a1;
b1 = b1*b1;
return(b1);
}
// [[Rcpp::export]]
IntegerVector fun(IntegerVector fun_data){
IntegerVector out = sapply( fun_data, fun1 ) ;
return(out);
}
然后,您只需 sourceCpp
您的文件并调用该函数:
And then, you can just sourceCpp
your file and invoke the function :
sourceCpp( "file.cpp" )
fun( 1:10 )
# [1] 1 4 9 16 25 36 49 64 81 100
这篇关于Rcpp + inline - 创建和调用附加函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!