7

Since last night I have been trying out Rcpp and inline, and so far I am really enjoying it. But I am kinda new to C in general and can only do basic stuff yet, and I am having a hard time finding help online on things like functions.

Something I was working on was a function that finds the minimum of a vector in the global environment. I came up with:

library("inline")
library("Rcpp")

foo <- rnorm(100)

bar <- cxxfunction( signature(),
'
Environment e = Environment::global_env();  
NumericVector foo = e["foo"];
int min;

for (int i = 0; i < foo.size(); i++)
{
    if ( foo[i] < foo[min] ) min = i;
}
return wrap(min+1);
', plugin = "Rcpp")

bar()

But it seems like there should be an easier way to do this, and it is quite slower than which.max()

system.time(replicate(100000,bar()))
   user  system elapsed 
   0.27    0.00    0.26 
system.time(replicate(100000,which.min(foo)))
   user  system elapsed 
    0.2     0.0     0.2 

Am I overlooking a basic c++ or Rcpp function that does this? And if so, where could I find a list of such functions?

I guess this question is related to: Where can I learn how to write C code to speed up slow R functions?

but different in that I am not really interested in how to incorporate c++ in R, but more on how and where to learn basic c++ code that is usable in R.

Community
  • 1
  • 1
Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
  • 1
    I highly doubt you'll speed up operations like min and max using C++ -- these are probably already implemented using (fast) SSE instructions in R. Plus, the transition from C++ to R and vice versa is not free. – Billy ONeal Mar 01 '11 at 17:57
  • I realize that, this is more meant conceptual, and this is part of a much larger c++ function I am trying to implement in R. – Sacha Epskamp Mar 01 '11 at 18:17

1 Answers1

10

Glad you are finding Rcpp useful.

The first comment by Billy is quite correct. There is overhead in the function lookup and there is overhead in the [] lookup for each element etc.

Also, a much more common approach is to take a vector you have in R, pass it to a compiled function you create via inline and Rcpp, and have it return the result. Try that. There are plenty of examples in the package and scattered over the rcpp-devel mailing list archives.

Edit: I could not resist trying to set up a very C++ / STL style answer.

R> src <- '
+   Rcpp::NumericVector x(xs);
+   Rcpp::NumericVector::iterator it =       // iterator type
+     std::min_element(x.begin(), x.end());  // STL algo
+   return Rcpp::wrap(it - x.begin()); '
R> minfun <- cxxfunction(signature(xs="numeric"), body=src, plugin="Rcpp")
R> minfun(c(7:20, 3:5))
[1] 14
R>

That is not exactly the easiest answer but it shows how by using what C++ offers you can find a minimum element without an (explicit) loop even at the C++ level. But the builtin min() function is still faster.

*Edit 2: Corrected as per Romain's comment below.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725