top of page

Speeding Up R Code with Rccp


Hello Agaaaaain

I'm soooo glad to be back and share something new with you guys.

It was almost 5 months ago, that I started to develope a new numerical model in R for one of my projects.

As soon as I started to work on that, I realized that something is wrong and that's the simulation speed. I had to use lots of loops for accomplishing some tasks and I was completely aware of its consequnces. But there was no any other way, or at least I used to think that. Finally, I reached to the point that my model was running well enough for my purpose but it was slow.

So as the next step, I started to imporve my model's performance by converting it to C++ and intergating it with R using Rccp package.

"The 'Rcpp' package provides R functions as well as C++ classes which offer a seamless integration of R and C++. Many R data types and objects can be mapped back and forth to C++ equivalents which facilitates both writing of new code as well as easier integration of third-party libraries" Dirk Eddelbuettel says about his package (https://cran.r-project.org/web/packages/Rcpp/index.html).

But, before you get into the very time consuming process of converting your code form R to C++ you need to make sure that it's exactly what you need for speeding up our code. What I'm trying to say is that there might be different ways for cleaning up your codes and wrtting high performance functions in R and using Rccp is just one of them.

I would be very happy to share what I have learned so far, but I will finish this post just by sharing a well known example of Rccp:


C++ file :

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]

double meanC(NumericVector x) {

int n = x.size();

double total = 0;

for(int i = 0; i < n; ++i) {

total += x[i];

}

return total / n; }

R :

x <- runif(1e5)

meanC(x)


Tags:

Featured Posts
Recent Posts
Archive
Search By Tags
bottom of page