Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the which() function with a pipe %>%

Tags:

r

dplyr

magrittr

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?

like image 521
braun_tube Avatar asked Sep 02 '25 17:09

braun_tube


2 Answers

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
like image 120
G. Grothendieck Avatar answered Sep 05 '25 07:09

G. Grothendieck


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
like image 33
Gregor Thomas Avatar answered Sep 05 '25 09:09

Gregor Thomas