Search code examples
rmagrittrinfix-operator

How to use `package::function()` inside a package when `function` is an infix operator?


According to H. Wickham's book R Packages, in the Package Metadata chapter, on how to add a package dependency, Hadley points out good reasons to explicitly refer to external functions using the syntax package::function().

Adding a package dependency here ensures that it’ll be installed. However, it does not mean that it will be attached along with your package (i.e., library(x)). The best practice is to explicitly refer to external functions using the syntax package::function(). This makes it very easy to identify which functions live outside of your package. This is especially useful when you read your code in the future.

From R Packages | Package metadata.

But how to do it when the function is an infix operator? For example, it seems I cannot do 1:10 magrittr::"%>%" sqrt? And adopting a function style here would defy the purpose of using the pipe operator... is it not?


Solution

  • I think you would be safe just using the import from magrittr there. But if you wanted you could just make sure that your symbol refers to the one you want by doing

    your_fun <- function(){
      `%>%` <- magrittr::`%>%`
      # now use %>% like you normally would
      # and you can be sure it refers to the magrittr version.
      return(42)
    }