rpipemagrittr

magrittr pipe placeholder doesn't work when calculating expression


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

Solution

  • From the ‘%>%’ help page:

    Using the dot for secondary purposes

    Often, some attribute or property of lhs is desired in the rhs call in addition to the value of lhs itself, e.g. the number of rows or columns. It is perfectly valid to use the dot placeholder several times in the rhs 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 to iris %>% subset(., 1:nrow(.) %% 2 == 0) but slightly more compact. It is possible to overrule this behavior by enclosing the rhs in braces. For example, 1:10 %>% {c(min(.), max(.))} is equivalent to c(min(1:10), max(1:10)).

    Therefore enclosing your function with {} works:

    c(10,22,35,46) %>% {(.[2] - .[1])}
    [1] 12