Combine logical vectors in list using logical OR

while picture while · Oct 8, 2013 · Viewed 8.9k times · Source

Question

How do I effectively combine logical vectors across the list using elementwise comparisons with logical OR (|). The result should be a logical vector of same length as the input vectors. If any of the input values is TRUE, the result is TRUE, else the result is FALSE.

Example

I have a list opts with a set of logical vectors of the same length.

> str(opts)
List of 5
 $ option1: logi [1:608247] FALSE FALSE FALSE FALSE FALSE FALSE ...
 $ option2: logi [1:608247] FALSE TRUE  FALSE TRUE  TRUE  TRUE  ...
 $ option3: logi [1:608247] FALSE TRUE  FALSE FALSE TRUE  FALSE ...
 $ option4: logi [1:608247] FALSE FALSE FALSE FALSE FALSE FALSE ...

and I want this as a result:

logi [1:608247] FALSE TRUE FALSE TRUE TRUE TRUE ...

Thus, the first value of the result, FALSE, is because the are no TRUE in the first position across all vectors of the list. The second value of the result, TRUE, is because the are two (at least one, any) TRUE in the second position of the vectors.

I am fine with changing my datastructure to be a matrix or data.frame or something else if it is better I just get this from a lapply.

Answer

Ricardo Saporta picture Ricardo Saporta · Oct 8, 2013

How about Reduce:

Reduce("&", opts)
Reduce("|", opts)