I have a vector vec like this vec <- c(1,4,5) and I want to check whether there are any steps down in the vector. I do this using:
any(diff(vec) < 0)
# [1] FALSE
No steps down. Okay. But when I try to use this code in a pipe I get a TRUE and an warning:
library(magrittr)
vec %>% diff() %>% any(. < 0)
# [1] TRUE
# Warning message:
# In any(., . < 0) : coercing argument of type 'double' to logical
How to correctly write any(diff(vec) < 0) as a pipe?
You have a couple of solutions already, but no explanation. The reason your original didn't work is that
magrittrpipes treat.differently when it is in a nested function call.By nested function call, I mean that
.is not an argument to the function that is the target of the pipe. Inany(. < 0), that function isany(), and its argument is. < 0, which is actually a function call to the<function. So the.is in a "nested function call".If
.is only in a nested function call, it is implicitly used as the first argument as well, so the codeis treated as
To suppress this weird behaviour, put the expression in braces, i.e. your example would be