Skip to content

Instantly share code, notes, and snippets.

@nanxstats
Forked from zjf/c_which.R
Last active December 7, 2018 20:41
Show Gist options
  • Save nanxstats/5393209 to your computer and use it in GitHub Desktop.
Save nanxstats/5393209 to your computer and use it in GitHub Desktop.
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