Skip to content
Prev 305989 / 398502 Next

effective way to return only the first argument of "which()"

On Thu, Sep 20, 2012 at 4:39 PM, Mike Spam <ichmagspam at googlemail.com> wrote:
5 hours and Dirk hasn't taken the bait? I suppose I'll give it a try,
though my Rcpp-fu is not great:

#####################

library(inline)
library(Rcpp)

## which.first() for R
which.first <- cxxfunction(signature(x = 'logical'), '
  NumericVector xx(x);
   // Rcpp magic which makes an integer vector xx from the SEXP x
  int i = 0;

  while(xx[i] != 1){
    i++;
  }
  return(wrap(i + 1)); // Remember, c++ indices are 0-based
', plugin = "Rcpp")

######################

This gives the first value for which x is true. If it's a specific
condition you are evaluating, you could push that logic down to C++
and put it inside the while loop as well to save time there but your
original post didn't say what the logic was.

Note that using this will require a working R development environment,
which is harder on some systems than others.

Cheers,
Michael