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