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 thepkgpackage. 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 thepkgnamespace ‘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) Error in foo(x) : could not find function 'foo' 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:pkg::foo(x) Error in loadNamespace(x) : there is no package called ‘pkg’- 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 thepkgnamespace
- After installing
Read more about namespaces in Advanced R and R packages.
-
If I am developing an R package, I can include
pkgfunctions in my package by usingroxygen2tags (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 includepkgin theDESCRIPTIONunderImports:
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)