Search code examples
rmagrittr

Use of ! (or any logical operator) with %>% (magrittr) produces unexpected output


I have run across a situation where %>% produces very surprising output when combined with !. Consider the following code:

x <- c(1:20)
y <- !is.na(x)

> y
 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE 
     TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

> sum(Y)
[1] 20

Ok, nothing surprising there. But if I try to shorten it using %>% weird stuff happens:

!is.na(x) %>% sum

[1] TRUE

TRUE?? Not what I expected - it should be 20.

If I remove the ! it gives me 0 as expected:

> is.na(x) %>% sum
[1] 0

and if I add brackets it works:

> {!is.na(x)} %>% sum
[1] 20

and treating ! as a function works:

> is.na(x) %>% `!` %>% sum
[1] 20

What is !is.na(x) %>% sum doing, and why does it return TRUE rather than 20?

EDIT: The other logical operators produce similar behavior:

> T&T %>% sum()
[1] TRUE
> {T&T} %>% sum()
[1] 1

> T|T %>% sum()
[1] TRUE
> {T|T} %>% sum()
[1] 1

Solution

  • I suspect that it's an order of operations issue:

    !is.na(x) %>% sum
    

    is evaluating to

    !(is.na(x) %>% sum)
    

    Which is equivalent to TRUE