# The power of Rcpp

**Quantitative thoughts » EN**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

While ago I built two R scripts to track OMX Baltic Benchmark Fund against the index. One script returns the deviation of fund from the index and it works fast enough. The second calculates the value of the fund every minute and it used to take for while. For example, it spent 2 minutes or more to get the values for one day. Here is an example of the result:

Following piece of code was in question:

^{?}View Code RSPLUS

for(y in 1:NROW(x)) { z=x[y,] if(as.numeric(z$last_price>0)) { if(as.numeric(z$bid>z$last_price))rez[y]=z$bid else if(as.numeric(z$ask>0 & z$ask<z$last_price))rez[y]=z$ask else rez[y]=z$last_price } else { rez[y]=(z$ask+z$bid)/2 } } |

The code above loops over time series and based on set of rules tries to decide which price (bid, ask or previous one) to use for calculations. Pure R script used to take 100 seconds to derive the price.

During the weekend I found time to watch very interesting Rcpp presentation. To my surprise, there are numerous ways to seamlessly integrate C++ into R code. So, I decided to rewrite the code above in C++ (Rcpp and inline packages were used).

^{?}View Code RSPLUS

#c++ code embed in code value code=' NumericVector bid(bid_);NumericVector ask(ask_);NumericVector close(close_);NumericVector ret(ask_); int bid_size = bid.size(); for(int i =0;i<bid_size;i++) { if(close[i]>0) { if(bid[i]>close[i]) { ret[i] = bid[i]; } else if(ask[i]>0 && ask[i]<close[i]) { ret[i] = ask[i];// } else { ret[i] = close[i];// } } else { ret[i]=(bid[i]+ask[i])/2; } } return ret; ' #a glue function between C++ and R getLastPrice = cxxfunction(signature( bid_ = "numeric",ask_ = "numeric",close_="numeric"),body=code,plugin="Rcpp") #and the call of the function getLastPrice(as.numeric(x$bid),as.numeric(x$ask),as.numeric(x$last_price)) |

What did I get in return? Well, 0.1 of a second instead of 100 seconds!

**leave a comment**for the author, please follow the link and comment on their blog:

**Quantitative thoughts » EN**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.