Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

logic

dplyr

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

like image 973
potockan Avatar asked Jun 08 '15 14:06

potockan


1 Answers

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?

like image 144
Ben Bolker Avatar answered Sep 27 '22 15:09

Ben Bolker