1
votes

When installing a package R will look at the 'Depends' and 'Imports' in the DESCRIPTION file to see which additional packages need installing.

When attaching 'library()' the package to an R session then R will load any packages listed under 'Imports' and attach any listed under 'Depends'.

My question is regarding importing functions in the NAMESPACE file? I'm confused as to the purpose of importing functions in that file and exactly what it's doing.

Are imported functions in the NAMESPACE file attached to the R session when the main package is attached?

If the answer is yes then is this not what 'Depends' is already doing? The only difference i can see is that individual functions can be attached to the session using NAMESPACE where as 'Depends' attaches the entire package.

1

1 Answers

2
votes

I would suggest reading the Namespaces chapter of Hadley's R Packages book. But in short, the answer is No.

Are imported functions in the NAMESPACE file attached to the R session when the main package is attached?

No, they are not. Imported functions are available for use in the package internals, but not attached to the user's search tree.

Another source for info is, of course, Writing R Extensions. They describe IMPORTS as:

The ‘Imports’ field lists packages whose namespaces are imported from (as specified in the NAMESPACE file) but which do not need to be attached.


As a demonstration, the current version of ggplot2, v 3.2.1, has import(scales) in its NAMESPACE file. In a fresh R session, we can load ggplot2 and observe that the scales package is not attached:

library(ggplot2)
percent(1)
# Error in percent(1) : could not find function "percent"
scales::percent(1)
# [1] "100%"

ggplot2 uses functions from scales internally, and can do so without using the package::function notation. This is what the import(scales) accomplishes. However, unlike with Depends, scales is not attached for the user.