Last active
December 16, 2015 06:39
-
-
Save zjf/5392833 to your computer and use it in GitHub Desktop.
An equivalent which() function in Rcpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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