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
.