Necroticka
Necroticka

Reputation: 285

How does R access the package namespace without a call to library?

I was helping somebody with their code recently and they asked me why it was possible to use functions from a certain package (e.g. dplyr) without explicitly 'loading' (and attaching them) to the search path within R.

Specifically, why it is possible to write:

dplyr::mutate(...)

As opposed to:

library(dplyr)

mutate(...)

When you use ::, it doesn't appear to automatically 'attach' the functions from the namespace dplyr onto the search path. That only happens when you call library(). This confuses me slightly: when you use the :: approach, how does R find the function mutate() within dplyr without it being attached to the search path?

Upvotes: 2

Views: 1313

Answers (1)

Konrad
Konrad

Reputation: 18657

You may also consider making use of with. with is traditionally is used to undertake operations on the data but combined with asNamespace can be used to access functions from the packages without the need to load the package.

with(asNamespace("dplyr"),
     select(mtcars, cyl) %>%
         mutate(cyl_two = cyl * 2)
)

You can use :: and ::: to access a single function from a package, accounting for exported or not exported functions. If you look at the code of double and triple colon operators you will see that those leverage very similar mechanism. Package name is used to construct an environment via asNamespace and get1 function is used to source the function.

Broadly speaking, a potentially efficient way of thinking about that is comparing package functions to objects in an environment. By calling ::, ::: or with we can reference those objects.


1 In case of :: the actual function is getExportedValue.

Upvotes: 2

Related Questions