rdplyrmagrittr

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


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?


Solution

  • 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