Writing an R package: should `:: ` be used for every external function?

I've been writing a package for work, so I've been looking up best practices for writing a package in R. I read the following quote from this blog:

When writing our package, the best practice is to refer to external functions using package::function() to make it easy to identify which functions are from other packages.

Is this advice generally correct? That is, should every function from an external library be called using the :: notation like foo::function()? Should library(foo) still be called?


I've started doing that for my own R code, just to help future me see where a command came from. Except the standard tidyverse commands - I don't do those.

1 Like

I don't think this advice is correct in general. It may be correct for their particular context, I don't know.

I thinks that in general this is somewhat subjective, and there are some tradeoffs to consider:

  • If you have name clashes (e.g. you use both pkg1::fun and pkg2::fun), then you need to use ::, you cannot import both functions.
  • If you use packages with function names that do not make it clear which packages they are in, then :: will make your code easier to read.
  • If you always use :: for a dependency that is not essential, then that dependency will not be loaded with your package (only when you first actually use it). This will make your package load faster. Sometimes much faster, because some popular packages load slowly, e.g. Matrix.
  • :: is slower than importing the function via NAMESPACE. (Haven't checked this recently, but I am pretty sure that it still holds.)
  • Importing means shorter code, so it is quicker to type. Sounds banal, but if you call a package many times, it does matter.

You should never use library(foo) in a package, you use Imports in DESCRIPTION and the NAMESPACE file instead (or roxygen2 to generate the NAMESPACE file). Or Imports and the :: notation if you go that way.


Thank you @Gabor and @Ajackson for your input! I'll take your thoughts into consideration and determine what will work best for my workflow based on your comments.

This topic was automatically closed after 45 days. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.