Search code examples
rmagrittr

How to make magrittr's pipe operator (%>%) work when nesting base-R functions?


Why does this code produce an error ?

library(magrittr)

c('a', 'b', 'c', 'b') %>% 
  seq_len(length(.))

# Error in seq_len(., length(.)) : 
#   2 arguments passed to 'seq_len' which requires 1

Solution

  • Another way could be to wrap in braces:

    c('a', 'b', 'c', 'b') %>% 
      {seq_len(length(.))}
    

    See: https://magrittr.tidyverse.org/reference/pipe.html

    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)).