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 withaaa == 4 %>% whichis passing4to thewhichfunction ...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?