我想知道是否有办法使用main函数中的Rcpp
包创建inline
函数。这是我想要做的一个例子:
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方法中创建自己的函数。如何创建并使用Rcpp
调用另一个inline
函数而不必将其传递给R?
答案 0 :(得分:14)
body
用于函数体,您要查看includes
的{{1}}参数:
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
Rcpp
版本的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
文件中编写代码,其中包含:
#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
您的文件并调用该函数:
sourceCpp( "file.cpp" )
fun( 1:10 )
# [1] 1 4 9 16 25 36 49 64 81 100