Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between loading and attaching in [R]

Tags:

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

like image 271
VivekDev Avatar asked Jun 03 '17 08:06

VivekDev


People also ask

Which function is used for loading packages in R?

There are basically two extremely important functions when it comes down to R packages: install. packages() , which as you can expect, installs a given package. library() which loads packages, i.e. attaches them to the search list on your R workspace.

How do you install and load the packages in R?

In R, you can easily install and load additional packages provided by other users. or click Tools > Install packages. Write the package name in the dialog, then click install. Once you install the package, you need to load it so that it becomes available to use.

What is library () function in R?

The library() and require() can be used to attach and load add-on packages which are already installed. The installed packages are identified with the help of the 'DESCRPTION' file which contains Build:field.


1 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()
like image 130
petermeissner Avatar answered Oct 11 '22 15:10

petermeissner