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

hon*_*oak 6 r rcpp

我想知道是否有一种方法可以Rcpp使用inlinemain函数中的 包创建函数.这是我想要做的一个例子:

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);
                           ")
Run Code Online (Sandbox Code Playgroud)

这应该导致:

> cpp.fun(a)
[1]  1  4  9  16  25  36  49  64  81  100
Run Code Online (Sandbox Code Playgroud)

但我知道编译器不会接受在main方法中创建自己的函数.如何创建和调用另一个Rcpp函数inline而不必将其传递给R?

Rom*_*ois 15

body是为了函数的主体,你想看看以下的includes参数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 )
Run Code Online (Sandbox Code Playgroud)

?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
Run Code Online (Sandbox Code Playgroud)

最后,你绝对应该看看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);
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以只sourceCpp调用您的文件并调用该函数:

sourceCpp( "file.cpp" )
fun( 1:10 )
#  [1]   1   4   9  16  25  36  49  64  81 100
Run Code Online (Sandbox Code Playgroud)