Other sites

using C++ within R

Introduction

Quite often I write which(...)[1] to find the first element of a vector matching some condition. One has to wonder whether that’s wasteful, though, since there is no need to do any tests once one works. I decided to try using C++, using Rcpp, to see if speed advances could be made.

Results

The C++ method was nearly twice as fast. However, other tests (with different
vector lengths, different fractions zeroed-out, etc) showed nearly identical
times for the two methods.

Conclusions

In light of variations in test results, and the added complexity of including
C++ code in an R program, I advise carrying out data-tailored benchmarks before
deciding to use Rcpp.

Note that the test does not account for the time to compile the C++ program,
which can outweigh time savings in small problems. However, this is irrelevant
because one shouldn’t be worrying about optimization in small problems anyway,
and large problems will likely involve package generation, which means that the
C++ compilation will be done as the package is being built.