Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

magrittr

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
like image 701
John Paul Avatar asked Jun 09 '16 17:06

John Paul


People also ask

What is the use of %>% in R?

%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression.

What is the output of a logical OR?

The logic or Boolean expression given for a logic OR gate is that for Logical Addition which is denoted by a plus sign, (+). Thus a 2-input (A B) Logic OR Gate has an output term represented by the Boolean expression of: A+B = Q.

Which logical operation outputs true if and only if one or more of its operands is true?

The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value.

What is the use of logical operators?

Logical Operators are used to perform logical operations and include AND, OR, or NOT. Boolean Operators include AND, OR, XOR, or NOT and can have one of two values, true or false.


1 Answers

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

like image 160
C_Z_ Avatar answered Oct 27 '22 00:10

C_Z_