[R] or of a logical vector

(Ted Harding) Ted.Harding at nessie.mcc.ac.uk
Thu Aug 5 21:22:12 CEST 2004


On 05-Aug-04 Ben Wittner wrote:
> Is there some fast (built-in?) way to get the OR of all the
> elements in a logical vector?
> 
> In other words, is there some fast (built-in) version of the function
> vor below?
> 
> Thanks.
> 
> -Ben
> 
> vor <- function(v) {
>   ans <- v[1]
>   if (length(v) > 1)
>     for (i in 2:length(v))
>       ans <- ans | v[i]
>   ans
> }

It's a sort of cheating ("type-punning"), but so long as it's just
the "or" you're after then

  sum(v)>0

will implement your 'vor', i.e. give you FALSE if all v[i]==FALSE,
and TRUE if any v[i]==TRUE. And it's certainly fast.

Similarly,

  prod(v)>0

would implement a 'vand'.

But you can also do these with 'any' and 'all', e.g.

  any(v==TRUE)

and

  all(v==TRUE)

I'm not sure which of these two approaches would be faster, but
I doubt there's much in it.

Best wishes,
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 167 1972
Date: 05-Aug-04                                       Time: 20:22:12
------------------------------ XFMail ------------------------------




More information about the R-help mailing list