[R] effective way to return only the first argument of "which()"
R. Michael Weylandt
michael.weylandt at gmail.com
Thu Sep 20 23:33:59 CEST 2012
On Thu, Sep 20, 2012 at 4:39 PM, Mike Spam <ichmagspam at googlemail.com> wrote:
> Thank you very much, especially Milan and Bert!
> I will do some speedtests and fit the function to my needs.
>
> I think the best way would be a modified function in C...
> But i am not familiar enough with C. Perhaps this would be a simple
> but useful extension.
> If someone has a solution, i would appreciate a post in this mailing list.
>
> Cheers and thanks to all,
> Nico
>
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
More information about the R-help
mailing list