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
%>% 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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With