Writing modular code with box
What is box
?
box
is a package…
How box
works
To understand how box
works, let’s refresh how we normally interact with packages and their functions when using R and developing packages:
Assume I want to use the
foo()
function from thepkg
package. The first step is to install it withinstall.packages("pkg")
-
To use the functions in
pkg
:I need to run
library(pkg)
in my R session, which loads thepkg
namespace ‘and attach[es] it on the search list.’-
If I try to use a function (
foo()
) from a package (pkg
) that hasn’t been loaded withlibrary(pkg)
orrequire(pkg)
, I see the following:foo(x) in foo(x) : could not find function 'foo' Error
This error can be confusing, because it’s not telling me if the package hasn’t been installed or if the package hasn’t been loaded.
-
If I try to use a function (
foo()
) from a package (pkg
) that hasn’t been installed withinstall.packages()
, I get the following error:::foo(x) pkgin loadNamespace(x) : there is no package called ‘pkg’ Error
- After installing
pkg
, I can get around usinglibrary(pkg)
by being explicit and usingpkg::foo()
, which tells R I want to use thefoo()
function from thepkg
namespace
- After installing
Read more about namespaces in Advanced R and R packages.
-
If I am developing an R package, I can include
pkg
functions in my package by usingroxygen2
tags (i.e.,#' @importFrom pkg foo
)When I use
devtools::document()
, the tags are converted into directives in theNAMESPACE
(i.e.,importFrom(pkg,foo)
)I also need to use
usethis::use_package("pkg")
to includepkg
in theDESCRIPTION
underImports:
The table below shows the connection between roxygen2
tags, the resulting NAMESPACE
entry, and what should be listed in the DESCRIPTION
(this is also covered in myPkgApp
)