Skip to main content

Posts

Showing posts from November, 2014

R and C++ integration: my first baby steps using inline

Hi, Really excited to try out stuff in Dirk's book. The first chapter of the book gives a gentle introduction to Rcpp and inline package. The problem setting is how to integrate a fibonacci recursive function in C++, compile it and execute it in R. Benchmarking results are also shown. The program code is all below in one R file. Its the same code in the book under listing 1.2 library(inline) library(rbenchmark) library(Rcpp) #inline function for fibonacci algorithm in C++ incltxt <- ' int fibonacci(const int x) {   if (x == 0) return(0); if (x == 1) return(1);   return fibonacci(x - 1) + fibonacci(x - 2); }' #wrapper function fibRcpp <- cxxfunction(signature(xs="int"),                        plugin="Rcpp",                        incl=incltxt,                         body=' ...

R benchmarking using proc.time() and rbenchmark package

I am the proud owner of Dirk's book on Seamless R and C++ Integration. Decided to dig right in and get into details on how to benchmark code from the first chapter on. Suppose you want to benchmark the following piece of R fibonacci code (1) fibR <- function(n) {      if(n == 0) return(0)      if(n == 1) return(1)      return (fibR(n - 1) + fibR(n - 2)) } You can use the good ol' proc.time() function like this (2) a <- proc.time() fibR(30) proc.time() - a Whose output will look something like this (3) user system elapsed 8.27 0.00 8.30 What this means is that the program took 8.27 user seconds to run the code and used 0 system seconds on resources in that time.  Ideally you need to add the user and system times to get the full picture of how long your code took to run. The elapsed time denotes the time it took for the day to go by between the first line of code in (2) to the 3rd line of code in (2). I...

Modify elements in a list using rapply

Using rapply one can write a function which runs over elements in a list returning a list. # Here I create a list of 10 normal random numbers testList <- list() testList[[1]] <- rnorm(10) testList[[2]] <- rnorm(10) # Here I replace all numbers which are < 0 by 0 newList <- rapply(testList, function(x) {ifelse(x<0,0,x)}, how = "list") Also if the data in the list is not a vector but a matrix newList <- function="" ifelse="" lapply="" p="" sapply="" testlist="" x="" y=""> # Here I add all elements using the Reduce function Reduce("+",newList)