Message-ID: <CAAmySGPuqKwmNR9V60dN6QpjBREdYpyop6rSGNeG=1EiUrRzow@mail.gmail.com>
Date: 2012-09-20T21:33:59Z
From: R. Michael Weylandt
Subject: effective way to return only the first argument of "which()"
In-Reply-To: <CAHQdM3Capw1FibgyYy4A6CExxcpUge+B0gKNsjjdmC_Qfmfb=A@mail.gmail.com>
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