Skip to content

Instantly share code, notes, and snippets.

@zjf
Last active December 16, 2015 06:39
Show Gist options
  • Save zjf/5392833 to your computer and use it in GitHub Desktop.
Save zjf/5392833 to your computer and use it in GitHub Desktop.
An equivalent which() function in Rcpp
cppFunction('
std::vector<int> c_which(NumericVector x, Function f, List args){
std::vector<int> ind = as< std::vector<int> >(f(x, args));
std::vector<int> out(ind);
std::vector<int>::iterator it;
int j = 0;
it = std::find(ind.begin(), ind.end(), 1);
while(it++ != ind.end()){
out[j++] = it - ind.begin();
it = std::find(it, ind.end(), 1);
}
out.resize(j);
return out;
}
')
foo1 = function(x, a)return(x[which(x > a)])
foo2 = function(x, a)return(x[c_which(x, function(x, bla){as.integer(x > bla)},a)]) ## 加上as.integer防止coerceToInteger报错。
require(rbenchmark)
set.seed(1001)
x = rnorm(1e+7)
benchmark(foo1(x, 0.1), foo2(x, 0.1), order = 'relative')[, 1:4]
## test replications elapsed relative
## 1 foo1(x, 0.1) 100 22.60 1.000
## 2 foo2(x, 0.1) 100 35.59 1.575
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment