test <- c(1,2,0,5,0)
which(test == 0)
test %>% which(.==0)
test %>% which(,==0)
test %>% which( ==0)
I am trying to figure out how to pipe a vector into the which() function. Using which(test == 0) gives me the desired result but using a pipe on the last three lines all give me errors. How can I get the same result as which(test == 0) but using a pipe?
Use {...} to prevent dot from being inserted into which
. Without the brace brackets it would have inserted dot as a first argument as in which(., . == 0)
.
library(dplyr)
test %>% { which(. == 0) }
## [1] 3 5
With magrittr we can use equals
library(magrittr)
test %>% equals(0) %>% which
## [1] 3 5
To use |> create a list containing test
where the component name is dot.
test |>
list(. = _) |>
with(which(. == 0))
## [1] 3 5
You have 2 functions, which
and ==
. But binary operator functions like +
, *
and ==
don't make much sense to pipe into.
> (test == 0) |> which()
[1] 3 5
> (test == 0) %>% which()
[1] 3 5
You can write test == 0
using normal function notation instead of the infix notation for binary operators, "=="(test, 0)
, and with that syntax you could pipe it all, but it kills the readability for me:
test %>% `==`(0) %>% which()
[1] 3 5
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