我们可以将Rcpp与多个C ++函数一起使用吗?
我用.c
语言构建自己的函数。 然后,我使用.C
来编写一个R函数来调用.c
函数,例如,
tmp <- .C("myfunction", as.integer(N), as.integer(n), as.integer(w1), as.integer(w2), as.integer(w3), PACKAGE = "mypackage")[[3]]
这被称为包裹Rfunction。 此外,我的function基于或要求其他.c
function。 据我所知,使用Rcpp
使它更Rcpp
,更容易,这样:
cppFunction('int add(int x, int y, int z) { int sum = x + y + z; return sum; }')
我也知道cppFunction
适用于C++
语言。 但是,我发现.c
函数和.c++
之间没有太大区别。
我的问题是:我可以将cppFunction
与我的.c
函数一起使用requrie wraper R函数吗? 或者我需要先将.c
函数转换为.c++
函数? 那么我的function所基于的其他function呢? 这会像任何常规的R
函数一样吗? 我的意思是:假设我有两个cppFunction
函数myfunc1
和myfunc2
,其中myfunc2
基于myfunc1
。 然后假设我的第二个cppFunction
如下:
cppFunction('int myfunc2(int x, int y, int z) { int sum = x + y + z; myfunc1 ## do some works here return something; }')
那会好吗? 或者我需要写如下:
cppFunction('int myfunc2(int x, int y, int z) { int sum = x + y + z; cppFunction('int myfunc2(int some arguments) {## do some works here} return something; }')
一般来说如何使用包含多个函数的build cppFunction
?
有什么帮助吗?
以下是使用外部cpp文件的示例。 这些函数可以在同一个文件中进行交互,但是像其他人一样,你必须使用header来使用其他文件中的函数。 在R中需要的任何函数之前,必须使用// [[Rcpp::export]]
。
(感谢@F.Privé改进代码)
1)文件cpp:
#include using namespace Rcpp; // [[Rcpp::export]] double sumC(NumericVector x) { int n = x.size(); double total = 0; for(int i = 0; i < n; ++i) { total += x[i]; } return total; } // [[Rcpp::export]] double meanC(NumericVector x) { return sumC(x) / x.size(); }
档案R:
Rcpp::sourceCpp("your path/mean.cpp") x <- 1:10 meanC(x) sumC(x)
2) 使用cppfunction的替代方法 。 你必须使用包含参数
cppFunction('double meanC(NumericVector x) { return sumC(x) / x.size(); }',includes='double sumC(NumericVector x) { int n = x.size(); double total = 0; for(int i = 0; i < n; ++i) { total += x[i]; } return total; }')
无论如何,我建议你使用sourceCpp,使用独立的文件可以产生更加可维护和干净的代码
3) 使用sourceCPP和多个cpp文件 。 您必须使用头文件并为要在其他cpp文件中使用的每个file.cpp执行头文件。
sum.h文件(ifndef防止多重定义)
#include #ifndef SUM1 #define SUM1 double sumC(Rcpp::NumericVector x); #endif
sum.cpp(像之前一样)
#include using namespace Rcpp; // [[Rcpp::export]] double sumC(NumericVector x) { int n = x.size(); double total = 0; for(int i = 0; i < n; ++i) { total += x[i]; } return total; }
mean.cpp文件(你必须包括sum头) #include“sum.h”
#include #include "sum.h" using namespace Rcpp; // [[Rcpp::export]] double meanC(NumericVector x) { return sumC(x) / x.size(); }