Rcpp +内联 - 创建和调用其他函数

时间:2012-12-19 16:01:08

标签: r rcpp

我想知道是否有办法使用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?

1 个答案:

答案 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
相关问题