body for the function body, you want to see the argument 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 )
?cxxfunction contains detailed documentation for the includes argument.
But keep in mind that in this version, changes will be made to your input vector, which is probably not what you want. Another version that also uses the Rcpp sapply version:
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
Finally, you should definitely take a look at sourceCpp . With it, you will write your code in a .cpp file containing:
#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); }
And then you can just sourceCpp create your file and call the function:
sourceCpp( "file.cpp" ) fun( 1:10 ) # [1] 1 4 9 16 25 36 49 64 81 100
source share