No, the user does not have to load the packages that are used by functions in my_package
.
The fact that you have listed a package under Imports:
in the DESCRIPTION
file means that during the installation of my_package
, R will check that this package is available on your system. This means then that functions in my_package
can use functions from these packages using the ::
notation, as you suggested.
Using the ::
notation is the recommended way to refer to functions from other packages, but there are also other options:
In order to make all the functions from, say, dplyr
accessable without ::
in my_package
, you could add import(dplyr)
to the NAMESPACE
file. This is convenient, if you use many functions from a package.
If you intend to use only, say, the function select
from dplyr
, you could add importFrom(select, dplyr)
to the NAMESPACE
file.
You could also add the package to the DESCRIPTION
file under Depends:
. This would mean that the package is loaded to the global environment when you use library(my_package)
. This is almost never a good solution.
The general idea of dependencies is R is that my_package
will have "it's own version" of the packages it depends on loaded. Therefore, you can always be sure that you will, e.g., use the function select()
from the dplyr
package, as you intended to do. The exception is the use of Depends:
which bypasses this system. In this case, my_package
will look for functions in the global environment and if somebody should have defined some function called select()
in the global environment, my_package
will use this function and you will get unexpected results.
Example 1:
DESCRIPTION
file:
Imports:
dpylr
some function from my_package
:
my_fun <- function(...) {
dplyr::mutate(...) %>%
dplyr::select(1:3)
}
Example 2:
DESCRIPTION
file:
Imports:
dpylr
NAMESPACE
file:
import(dplyr)
some function from my_package
:
my_fun <- function(...) {
mutate(...) %>%
select(1:3)
}
Example 3:
DESCRIPTION
file:
Imports:
dpylr
NAMESPACE
file:
importFrom(dplyr,select)
some function from my_package
:
my_fun <- function(...) {
dpylr::mutate(...) %>%
select(1:3)
}
You find more detailed explanations of how to handle dependencies in R packages on the web. For instance the following are useful:
Also, it is not necessary to write the NAMESPACE
file by hand. You can let roxygen2
do that for you. Read the documentation for more information.