Search code examples
rlogictruthiness

What does multiple %in% in a row test?


Consider:

a <- c("a", "b", "c")
b <- c("a", "e", "f")
c <- c("a", "h", "i")

> a %in% b %in% c
[1] FALSE FALSE FALSE

I would have expected this to evaluate to TRUE FALSE FALSE, since the first element in each vector is "a". Why is this not the case?


Solution

  • What you are doing is first this operation: a %in% b resulting in TRUE FALSE FALSE. Then you basically do the chain c(TRUE,FALSE,FALSE) %in% c, which of course, will result in all False.

    You can try this to get the wanted vector of boolean (taking into account the position):

    a == Reduce(function(u,v) ifelse(u==v, u, F), list(a,b,c))
    #[1]  TRUE FALSE FALSE
    

    If you want common elements, not depending on the position, you can do:

    Reduce(intersect, list(a,b,c))