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