0

I set out trying to find the difference between library() and require() and I found a post on here that explains it well: What is the difference between require() and library()?

On this post they talk about how you would use require() in a function and library() at the top of a script. This posses my question: What is the purpose of loading packages in a function versus at the top of the script? What benefit is there in doing that?

Thanks!

  • 5
    It's a matter of style. Sometimes the purpose of the code determines the style. For example, when writing a package, it's common to use `::` notation, as it makes managing imports easier. In analysis scripts, putting all the packages loaded at the top will generate an error right away if you're missing a package. Actually putting a `library` call in a function is generally bad form, as it's a side-effect, not an explicit call, and thus makes seeing dependencies harder when reading code. – alistaire Jun 25 '18 at 19:07

1 Answers1

0

To elaborate further on the comment of @alistaire, I think the important part is to use :: notation where possible (sorry for making this an answer, however, I wanted to use some code that does not fit into a comment). The general idea is to keep your NAMESPACE as clean as possible and only call specific functions when needed, i.e., use them temporarily and do not load them permanently in the current session. Of course, they still need to be installed on the sytem for being able to load them. Temporary loading avoids conflicts or other side effects, e.g., when two different packages use the same name for functions that, however, do different things.

For illustration of the issue regarding the namespace you may check below code, you will need to have the library stringi installed, which I just used as an example. I hope this helps.

# load a library and check if its loaded
library(stringi)
names(sessionInfo()$otherPkgs)
# [1] "stringi"
# detach it
detach("package:stringi", unload = TRUE)
names(sessionInfo()$otherPkgs)
# NULL

# use library with :: notation, e.g., within function
my_fun <- function(x) {
  stringi::stri_replace_all_fixed(x, "a", "b")
}
my_fun("aaa")
# [1] "bbb"

# check if library is loaded
names(sessionInfo()$otherPkgs)
# NULL -> it is not loaded, hence, the namespace is kept clean
Manuel Bickel
  • 2,156
  • 2
  • 11
  • 22