John John - 1 month ago 5
R Question

R how to use logical AND as a function

If I have a vector of logical statements, like

x>1
,
y!=1
and
sin(x)<0
, is there a function in R could do like

AND(x>1, y!=1, sin(x)<0)


with the same results as

x>1 & y!=1 & sin(x)<0

Answer

Yes, we can use Reduce and "&":

AND <- function (...)  Reduce("&", list(...))

Example:

AND(1 < 4, 5 > 7, 6 == 6)
# [1] FALSE

The binary operator "&" only works with two inputs, so we can do

"&"(1 < 4, 5 > 7)

but not

"&"(1 < 4, 5 > 7, 6 == 6)

Reduce is here to help, by iteratively applying "&":

tmp <- "&"(1 < 4, 5 > 7)
"&"(tmp, 6 == 6)