Why {magrittr}
's pipe placeholder doesn't work when used in artihmetic expressions?
c(10,22,35,46) %>% .[1] # 10
c(10,22,35,46) %>% .[2] # 22
c(10,22,35,46) %>% (.[2] - .[1]) # Error: object '.' not found
From the ‘%>%’ help page:
Using the dot for secondary purposes
Often, some attribute or property of
lhs
is desired in therhs
call in addition to the value oflhs
itself, e.g. the number of rows or columns. It is perfectly valid to use the dot placeholder several times in therhs
call, but by design the behavior is slightly different when using it inside nested function calls. In particular, if the placeholder is only used in a nested function call,lhs
will also be placed as the first argument! The reason for this is that in most use-cases this produces the most readable code. For example,iris %>% subset(1:nrow(.) %% 2 == 0)
is equivalent toiris %>% subset(., 1:nrow(.) %% 2 == 0)
but slightly more compact. It is possible to overrule this behavior by enclosing therhs
in braces. For example,1:10 %>% {c(min(.), max(.))}
is equivalent toc(min(1:10), max(1:10))
.
Therefore enclosing your function with {} works:
c(10,22,35,46) %>% {(.[2] - .[1])}
[1] 12