-
-
Save nanxstats/5393209 to your computer and use it in GitHub Desktop.
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
library("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) x[which(x > a)] | |
# use as.integer to avoid coerceToInteger errors | |
foo2 <- function(x, a) x[c_which(x, function(x, bla) as.integer(x > bla), a)] | |
library("rbenchmark") | |
set.seed(1001) | |
x <- rnorm(1e+7) | |
all.equal(foo1(x, 0.1), foo2(x, 0.1)) | |
# [1] TRUE | |
benchmark(foo1(x, 0.1), foo2(x, 0.1), order = "relative")[, 1:4] | |
# test replications elapsed relative | |
# 1 foo1(x, 0.1) 100 8.971 1.000 | |
# 2 foo2(x, 0.1) 100 33.778 3.765 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment