rlogical-operators

comma, AND and vertical bar operator "|"


This may seem like a stupid question, please bear with me. I wanted to confirm what a comma evaluates to so I did the following.

xy <- c(1:10)
ab <- c(10, 2, 1, 6, 8, 6, 7, 2, 10, 6)

# I ran this knowing the number 3 is absent in `ab`
3 %in% c(xy, ab) # output `TRUE` so I thought it evaluates to an OR

# Ran this
3 %in% c(xy & ab) # output `FALSE` as expected

# then ran this
3 %in% c(xy | ab) # output `FALSE` then I got confused, I was expecting same output as in the comma code

I am thinking the c() function maybe responsible. Can anyone please help me understand?


Solution

  • I think Jon Spring has already explained almost everything in his excellent comment. Your last command:

    3 %in% c(xy | ab) # output `FALSE`
    

    returns FALSE and was unexpected to you, I think because you may have incorrectly assumed that the command reads: "Is the number 3 in xy, or is it in ab? This would be written in R code as:

    (3 %in% xy) | (3 %in% ab)
    

    which does return TRUE (your expectation).

    The issue here is that xy | ab is evaluated first and returns a vector of length 10, all of which are TRUE. Then R determines whether 3 is in that vector, and returns FALSE.

    You can combine xy and ab first, using c() with no OR:

    ## these are equivalent to `3 %in% xy | 3 %in% ab`
    3 %in% c(xy, ab)
    3 %in% union(xy, ab)
    

    But this only works because what you're doing is checking set membership.