Search code examples
rvectorlogical-operators

elementwise and on multiple vectors in R


I have several vectors and I would like to & them together (i.e. I would & all the the first elements of each vector, all the second, etc.). Assume they are all of equal length. The result should be a logical vector of the same length as the individual vectors.

I thought of doing this but it did not work:

a = c(NA, 1, 2, 3)
b = c(0, 1, 2, 3)
d = c(NA, 1, NA, 3)
do.call("&", list(a, b, d))
# Error in do.call("&", list(a, b, d)) : binary operations require two arguments

Solution

  • I think you want Reduce().

    Reduce("&", list(a, b, d))
    # [1] FALSE  TRUE    NA  TRUE
    

    This applies & element-wise down the list. Check against

    v <- logical(4)
    for(i in 1:4) v[i] <- a[i] & b[i] & d[i]
    v
    # [1] FALSE  TRUE    NA  TRUE
    

    In fact the for() loop might even be faster than Reduce(). I'll leave the benchmark to you.