Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel 'or' operation on many logical vectors

In R, I have a number of logical vectors, or varying number (ie sometimes 1, sometimes n vectors), they are guaranteed to be ALL of the same length, I need to produce a single vector of the same length as the input vectors, where each element is to be TRUE if any of the vectors at the same element index are TRUE, else FALSE.

I am wondering if there is a builtin operation, or simpler method, to achieve what I want. Below is what I have so far, for 3 vectors.

set.seed(1) #For reproducability
o = c(T,F)
l = 10
A = sample(o,l,replace=T)
B = sample(o,l,replace=T)
C = sample(o,l,replace=T)
fun = function(...) apply(do.call(cbind,args = list(...)),1,any)
fun(A,B,C) ##Produces Desired Result
like image 967
Nicholas Hamilton Avatar asked Oct 24 '25 14:10

Nicholas Hamilton


1 Answers

We can use Reduce with |

Reduce(`|`, list(A, B, C))

Or with rowSums

rowSums(cbind(A,B,C))!=0

If there are only 3 vectors, a compact option would be

!!(A+B+C)
like image 145
akrun Avatar answered Oct 27 '25 03:10

akrun