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

55 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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 !.

0
On

With %>%, we can use the negate (!) also in chaining

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

Or use the aliases from magrittr

c(1, 2, 3, 4) %>%
   equals(1) %>% 
   not %>%
   sum
#[1] 3