andrewH
andrewH

Reputation: 2321

Using single functions from a package

Using individual functions from an unloaded package

As time has gone by I find myself loading more and more packages at the beginning of an R session. Just loading the tidyverse loads more packages than used to be my norm. Because of this, I find myself increasingly likely to be hit by function name conflicts. Especially when I did not notice those conflicts during package loading these can create confusing results and strange errors. So I am wondering if I can, in general, just import the particular function I want to use, without loading the package from which it comes.

More precisely, if this_pack is a package that is locally installed but not loaded, and this_fn() is an exported function in this_pack, can I safely expect this_pack::this_fn() to work, and to work in the same way as it would if the entire package were loaded? I know it usually does, but I want to know if there are times I should expect it to fail.

See the answers to related questions for additional information:

I've accepted the answer of user2554330, which I think would not be an answer to the other questions referenced. Still, they provide interesting, and related, information on other reasons to or not to use ::, so I think keeping the cross-reference is probably a good idea. I've incorporated them above.

Upvotes: 0

Views: 708

Answers (1)

user2554330
user2554330

Reputation: 44788

Yes, nowadays it should always be safe to call this_pack::this_fn(). If this_pack was not loaded, this will load it (all of it). (Remember that loading and attaching a package are different! Loading it gets it in memory, but not on the search list. Attaching it puts it on the search list.) This may make the first call a little slow, but the package will stay loaded, so subsequent calls will be faster. It used to be the case that evaluating :: took a noticeable amount of time in every call, but I think just-in-time compiling has mostly removed that. But if you want, you can get a local copy using

local_copy <- this_pack::this_fn

and then make calls to local_copy() without paying for the :: lookup again.

Since all packages have namespaces, any calls made by this_pack::this_fn() (or local_copy()) will go to the right place, unless the author of the package tries really hard to subvert the normal mechanisms.

If you are writing a package yourself, you can import just that one function. This will mean that loading your package will trigger a load of this_pack: so your load will be a bit slower, but the first call to this_fn() will be faster.

Upvotes: 3

Related Questions