Difference between loading and attaching in [R]

Viewed 1988

In RStudio, when I check and uncheck a package, I see the following commands.

library("ggplot2", lib.loc="~/R/win-library/3.4")
detach("package:ggplot2", unload=TRUE)

Can someone explain what is unload=TRUE does?

Conceptually is there a difference between loading/unloading vs attaching/detaching?

RStudio Attaching and Loading of packages

2 Answers

From R's official help pages (see also R Packages - Namespaces):

Anything needed for the functioning of the namespace should be handled at load/unload times by the .onLoad and .onUnload hooks.

For example, DLLs can be loaded (unless done by a useDynLib directive in the ‘NAMESPACE’ file) and initialized in .onLoad and unloaded in .onUnload.

Use .onAttach only for actions that are needed only when the package becomes visible to the user (for example a start-up message) or need to be run after the package environment has been created.

 

  • attaching and .onAttach
    • thus means that a package is attached to the user space
    • aka the global environment
    • usually this is done via library(pkg)
    • and you can use normal fun() syntax

 

  • loading and .onLoad
    • thus means that package is (in any way) made available to the current R-session
    • (e.g. by loading/attaching another package that depends on it or by using pkg::fun() syntax the first time)
    • though you will not find functions in the global environment
    • you can use pkg::fun()

detach related to package environment(which more related to user)
unload = TRUE related to namespace environment(which more related to other package)

after detach, you can not use any function inside that package directly but unloadnamespace won't prevent you from calling that function,but the other packages can't use its function directly

Related