Search code examples
rdplyrmagrittr

rhs of magrittr pipe returns FALSE when lhs is placed in !()


I encountered an issue using the magrittr %>% where an unexpected output is produced when the lhs is wrapped in !(). For example, I expected the output of these two lines to be identical.

sum( !( c(1,2,3,4) == 1 ) )

!( c(1,2,3,4) == 1 ) %>% sum()

However, the first line returns "3", as expected, whereas the second line returns "FALSE". Why is that?


Solution

  • The issue is of precedence, wrap (..) around the first expression and it behaves as expected.

    (!(c(1,2,3,4) == 1)) %>% sum
    #[1] 3
    

    You can find the precedence table at ?Syntax where you can see that %any% is of higher precedence than !.