简体   繁体   中英

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 (ie, 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?

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

You can't use package::infix it with the infix syntax, but you can use infix operators with standard syntax. For example:

"+"(1, 2)
# [1] 3

Hmisc::"%nin%"(1:3, 2)
# [1]  TRUE FALSE  TRUE

Unfortunately, this doesn't work with magrittr when the package isn't loaded, probably due to its substitution tricks.

## what a shame that this beauty doesn't work:
magrittr::"%>%"(1:5, mean)
# Error in pipes[[i]] : subscript out of bounds

library(magrittr)
"%>%"(1:5, mean)
# [1] 3

In a package context, I would recommend just importing magrittr , or at least importing "%>%" .


The source you quote is good enough to explain some of the reasoning behind this best practice:

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.

This doesn't seem to apply in this case. You are unlikely to forget where %>% came or to mistakenly think that it is created in your package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM