There are a few things that I would do differently, especially after just a casual look at the Rcpp documentation. So here is just a quick list:
- Yes, we can make cycles faster. Often a lot.
- Yes, we can return atomic types of C / C ++, as well as vectors. There are many examples. For these non-vector types,
wrap() ; double vectors are returned automatically. But you never use new / delete . See Writing R Extensions for what. - Yes, you can use the built-in package. And we use it a lot. But we never use it with the
.C() cfunction() from cfunction() . Always use cxxfunction() or at least include .Call() . I'm not sure how you missed it. - Since Rcpp is 0.10.0, we have Rcpp attributes that are even easier to use than inline and
cxxfunction() . Look around, for example, on sourceCpp() or cppFunction() , or even read the vignette. - Finally, you really lack elementary things. Have you read the Rcpp-iintroduction PDF vignettes and / or the Rcpp-FAQ?
Edit: Ok, here is a complete example following the structure of your function (but we can do better, see below):
#include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector monkey(NumericVector ary) { int lens = ary.length(); // objects can tell you about their length double res=0; for(int j=0;j<lens;j++) res += ary[j]; res /= (double) lens; NumericVector rary(lens); for(int i=0;i<lens;i++) rary[i] = ary[i]-res; return rary; } // and we even include some R code to test automagically /*** R set.seed(42) x <- rnorm(5)
which, if you call it, also runs the R code below:
R> Rcpp::sourceCpp('/tmp/monkey.cpp') R> set.seed(42) R> x <- rnorm(5)
But one of the key functions of Rcpp is that you can even perform a vector operation in C ++:
R> cppFunction('NumericVector monkey2(NumericVector x) { return x - mean(x); }') R> monkey2(x) [1] 0.9296545 -1.0060021 -0.0781755 0.1915587 -0.0370356 R>
It just compiled a new single-line C ++ function that worked on the whole vector x and ran it.
source share