How to use logical functions with %>% operator (dplyr)

1.4k views Asked by At

I was wondering how to use logical (for example which, any, all) functions with %>% operator from dplyr package in R. I have a vector of values

aaa <- sample(1:5, 10, replace = TRUE)

I would like to find out which of them are equal to 4. When I try this:

aaa == 4 %>% which(.)

I get the following error:

Error in which(.) : argument to 'which' is not logical

The same goes with other functions which require logical vector as an argument, such as all or any.

aaa == 4 %>% any

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE

Warning message: In any(.) : coercing argument of type 'double' to logical

2

There are 2 answers

1
Ben Bolker On BEST ANSWER

I think it's just an operator precedence issue. The %>% operator has lower precedence than other operators such as ==, so what you're actually doing with aaa == 4 %>% which is passing 4 to the which function ...

(aaa == 4) %>% which

seems to work just fine ...

This use of %>% seems a little odd/unnecessary, but maybe that's just because you've isolated it from your workflow in order to create a reproducible example. Maybe you could say a little more about the context?

0
BartekCh On

Use brackets around logical operations.

aaa <- sample(1:5, 10, replace = TRUE)
(aaa == 4) %>% which(.)
[1]  7  9 10
(aaa == 4) %>% which()
[1]  7  9 10
(aaa == 4) %>% any()
[1] TRUE