Running
TRUE |> `!`()
Results in:
Error in !NULL : function '!' not supported in RHS call of a pipe (<input>:1:9)
When using magrittr
, there is a not()
alias, but this does not work for base R. See: Negation `!` in a dplyr pipeline `%>%`
Running
TRUE |> `!`()
Results in:
Error in !NULL : function '!' not supported in RHS call of a pipe (<input>:1:9)
When using magrittr
, there is a not()
alias, but this does not work for base R. See: Negation `!` in a dplyr pipeline `%>%`
Simply adding brackets:
TRUE |> (`!`)() #[1] FALSE
!TRUE
. You get an extra function call - the parentheses function - as this is interpreted as `(`(`!`)(TRUE)
. R is weird.Negate()
One base R approach is to Negate()
the identity()
function:
TRUE |> Negate(identity)() # [1] FALSE
This is parsed as Negate(identity)(TRUE)
, i.e. !TRUE
.
isFALSE()
Alternatively, you can use isFALSE()
, though this is limited to vectors of length one:
TRUE |> isFALSE() # [1] FALSE
If you have a longer logical vector, v
, you can *apply()
this function. It's important to be aware that this is stricter than Negate()
, both in terms of how it handles NA
and how it treats other truthy/falsy values:
# NA values v <- c(TRUE, NA, FALSE) v |> Negate(identity)() # [1] FALSE NA TRUE v |> sapply(isFALSE) # [1] FALSE FALSE TRUE # Other falsy values e.g. 0 handled differently 0 |> Negate(identity)() # [1] TRUE 0 |> isFALSE() # [1] FALSE
This is explicit, but whether its treatment of NA
is desired will depend on your goal.
xor()
Finally, if you want to be perhaps a little too clever about it, you can use xor()
, taking advantage of the fact that xor(x, TRUE)
is equivalent to !x
, because:
x | y | xor(x, y) |
---|---|---|
FALSE | TRUE | TRUE |
TRUE | TRUE | FALSE |
v <- c(TRUE, NA, FALSE) v |> xor(TRUE) # [1] FALSE NA TRUE identical(v |> xor(TRUE), !v) # [1] TRUE
Why not define not()
yourself?
not <- function(x) !x TRUE |> not()
It's
> TRUE |> base::`!`() [1] FALSE
::
. R does not parse this as !TRUE
but as `::`(base, `!`)(TRUE)
.With the native base R pipe operator you can do
TRUE |> { \(.) !. }() # [1] FALSE
If this is useful depends on the task.
|>
pipe, I don't see a reason why. You can dofun <- `!`; TRUE |> fun()
.