【问题标题】:Rcpp + inline - creating and calling additional functionsRcpp + inline - 创建和调用附加函数
【发布时间】:2012-12-19 16:01:07
【问题描述】:

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

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?

【问题讨论】:

    标签: r rcpp


    【解决方案1】:

    body是函数体,你要看cxxfunctionincludes参数:

    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
    

    【讨论】:

      猜你喜欢
      • 2013-11-13
      • 2014-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      相关资源
      最近更新 更多