Find the Minimal Vector in Rcpp

I tried Rcpp and inline from last night, and so far I really like it. But I'm actually new to C in general, and I can only do basic things, and it's hard for me to find help on the Internet on things like functions.

Something I worked on was a function that finds a minimum of a vector in a global environment. I figured it out:

 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 rather 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 

I don’t notice the underlying c++ or Rcpp that does this? And if so, where can I find a list of such functions?

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

but it differs in that I’m not very interested in how to include c++ in R , but more on how and where to learn the basic c++ code that can be used in R

+6
c ++ r rcpp
source share
1 answer

Glad you found Rcpp useful.

Billy's first comment is quite correct. There is overhead in the function search, and overhead in the search for [] .

In addition, a much more general approach is to take the vector that you have in R, pass it to the compiled function that you create using the built-in and Rcpp, and return the result. Try this. There are many examples in the package and are scattered across the archives of the rcpp-devel mailing list.

Edit: I could not resist trying to tweak the response to the C ++ / STL style.

 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> 

This is not the easiest answer, but it shows how, with what C ++ offers, you can find a minimal element without a (explicit) loop, even at the C ++ level. But the built-in min() function is even faster.

* Edit 2: Fixed as per Romain comment below.

+9
source share

All Articles