How to use `package::function()` inside a package

2020-04-18 06:00发布

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?

2条回答
时光不老,我们不散
2楼-- · 2020-04-18 06:22

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)
}
查看更多
霸刀☆藐视天下
3楼-- · 2020-04-18 06:37

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.

查看更多
登录 后发表回答