Skip to main content

New behooveful features for {box} modules

Other ways to write {box} modules

Packaging, lazy imports, and native code for {box} modules.
R
box
programming
modules
packages
Author

Joshua Marie

Published

October 12, 2026

1 Hear me out first

R keeps growing, and its ecosystem is a big part of why. A talented community keeps writing R code that improves the language for everyone else, and it ships that code as R packages. Reusable code can be organized in a few ways, but I am not fond of the native options. I even ranked the ways to import R packages in an earlier post, with the native functionality at the bottom of the list.

First of, native R’s library(). It attaches a package’s exported names to the search path, which is not the same as importing them into a local scope. The attached package:dplyr environment sits right after the global environment, so code anywhere in your session sees those names. The problem is that this causes namespace collisions, which in an example scenario where you are attaching dplyr, the attachment then masks filter() and lag() from {stats}. You also cannot confine an attach to a function. Take this example:

cv_data = function(data, ...) {
    library(dplyr)
    library(tidyr)
    library(tidyselect)
    # library(tidyverse) if you are self-loathing

    data |>
        select(...) |>
        select(where(is.numeric)) |>
        pivot_longer(
            cols = everything(),
            names_to = "var",
            values_to = "val"
        ) |>
        group_by(var) |>
        summarise(
            # .by = ,   # if you don't want to supply the grouping var through `group_by()`
        
            m = mean(val, na.rm = TRUE),
            sd = sd(val, na.rm = TRUE),
            cv = (sd / m) * 100
        )
}

So, when you run an iris |> cv_data(everything()) instance, it works but it also leaves dplyr and tidyr attached for the rest of the session, so the imports leak out of the function. The native :: operator (dplyr::select()) avoids the attach, but it gets noisy in pipelines and gives you no aliasing or selective import. Oh well, you could by assigning it into a variable, e.g. keep_when = dplyr::filter, but it’s dirty and more laborous. With box, this reduces those shortcomings — we have box::use(dplyr[select, group_by, keep_when = filter]) that gives you both.

How about working with local R codes? Then there is source() for that job. By default, it evaluates in the global environment (local = FALSE). With local = TRUE it evaluates in the calling environment instead, but you still get no namespace, no explicit import list, and no way to tell where a name came from. Neither library() nor source() makes R modular. Actually speaking, there are so many shortcomings from this function but my only gripe is it has too many parameters — 17 to be exact — and there’s no way I can remember them at once (I have to reach out its documentation through ?source() but it doesn’t help me at any case).

Second, little in native R is ergonomic for writing and organizing code. After years of experience using R, but its package system, I have been observing its flaws and shortcomings and here’s my list:

  1. Its package do not support hierarchical nesting of code, so you won’t see submodules and such in traditional R packages (polars is odd as it uses a different but “mystical” approach to store the main public APIs in a pl environment). The source container is the flat R/ directory, an awkward constraint (Disclaimer: in my opinion) when you come from Python, where folders and scripts map directly onto nestable packages and modules.

  2. They need boilerplate, namely DESCRIPTION, NAMESPACE, and other plenty of structures, mostly in a formal package structure, and they have to be used even for a small reusable unit. usethis and roxygen2 helps you most of it, so this is not a huge deal, but it is still friction.

You don’t do this on box at all. {baler} only requires 1 file and then the folder which contains the source codes, nothing else, in order to package box modules.

  1. Source files in a CRAN-style package are evaluated into one shared package namespace. The order follows the Collate field in DESCRIPTION, and without it, files are evaluated by the lexicographical/alphabetical order of the file name (see the roxygen2 article on collation). This gets more annoying as the code grows.

By contrast, each box module lives in its own isolated namespace and is loaded with box::use(), not sourced into the calling environment.

2 “Futuristic” Features

I have been using to box lately, because I want a better way to write, organize, and reuse R code, and I have wanted it for years. In fact, I bestow some little to plenty contributions on this package. Over a year now (before I wrote this blog), I (though we started as a team, I am only left just for now) embarked a project called {baler} (started as carrier BTW), which is written in Rust with a thin CLI wrapper, to package and distribute box modules. There is no formal name for these packages, so I call them box-bale modules for now. I am biased, but I recommend writing packages this way.

TipIn a nutshell

I won’t list every reason here (the official documentation does), but in a nutshell, its packages resemble Python’s packaging system, and its logic and interface, it takes versioning seriously, and you can lock the dependency structure of box-bale modules.

{baler} is made to give box modules a chance to be a package, the way Python modules are, and I also contributed to box itself a bit. There, I proposed lazy imports through a lazy() call and plug the declared import within it. The idea comes from PEP 810, which shipped in Python 3.15 in October 2026 with the lazy soft keyword. Since box::use() is an ordinary R function call, a keyword is not an option, so lazy() function call is the R adaptation. I’ll discuss it later.

These new features in box are not just something I want. I need them (as the title suggests).

SpongeBob meme: I need it

3 Making packages out of them

With {baler}, you can now turn box modules into packages, with a procedure close to Python’s. I like it because modules can be nested, and scripts and folders can depend on each other. If I were to remake the tidyverse from a meta package into an actual module that syncs with {baler}, this would be the structure:

tidyverse/
├── __init__.r                          # Top-level facade: re-exports the main packages
│
├── dplyr/
│   ├── __init__.r                      # Public dplyr API
│   ├── verbs/
│   │   ├── __init__.r
│   │   ├── rows.r                      # filter, arrange, distinct, slice_*, sample_*
│   │   ├── columns.r                   # select, rename, relocate, mutate, transmute, pull
│   │   ├── groups.r                    # group_by, ungroup, summarise, reframe, count, tally, rowwise
│   │   └── joins.r                     # *_join, bind_rows, bind_cols, set operations
│   ├── helpers/
│   │   ├── __init__.r
│   │   ├── select.r                    # tidyselect helpers (starts_with, where, etc.)
│   │   ├── vector.r                    # if_else, case_when, coalesce, between, lead/lag, ranking
│   │   └── context.r                   # n(), cur_*, across, c_across, pick
│   ├── backend/                        # Lower-level / less common (optional)
│   │   └── __init__.r
│   └── data.r                          # starwars, storms, band_members, etc.
│
├── tidyr/
│   ├── __init__.r
│   ├── pivoting.r                      # pivot_longer, pivot_wider
│   ├── nesting.r                       # nest, unnest, unpack, hoist
│   ├── missing.r                       # drop_na, fill, replace_na
│   ├── expanding.r                     # complete, expand, crossing, nesting
│   ├── separating.r                    # separate, unite, extract, separate_rows
│   └── helpers.r                       # everything else (chop, pack, etc.)
│
├── ggplot2/
│   ├── __init__.r
│   ├── core.r                          # ggplot, aes, %+%, layer
│   ├── geoms/
│   │   ├── __init__.r
│   │   ├── basic.r                     # geom_point, geom_line, geom_bar, geom_col, geom_histogram...
│   │   ├── statistical.r               # geom_smooth, geom_boxplot, geom_violin, geom_density...
│   │   └── specialized.r               # geom_sf, geom_raster, geom_tile, etc.
│   ├── scales/
│   │   ├── __init__.r
│   │   ├── continuous.r
│   │   ├── discrete.r
│   │   └── date.r
│   ├── themes/
│   │   ├── __init__.r
│   │   ├── built_in.r                  # theme_bw, theme_minimal, theme_void...
│   │   └── elements.r                  # theme(), element_*, margin, etc.
│   ├── coords.r                        # coord_cartesian, coord_flip, coord_polar, coord_sf...
│   ├── facets.r                        # facet_wrap, facet_grid
│   ├── stats.r                         # stat_*, position_*
│   └── guides.r                        # labs, guides, guide_*
│
├── tibble/
│   ├── __init__.r
│   ├── constructors.r                  # tibble, tribble, as_tibble, enframe, deframe
│   ├── subsetting.r                    # [, [[, $, add_row, add_column
│   └── printing.r                      # print methods, glimpse, view
│
├── readr/
│   ├── __init__.r
│   ├── readers.r                       # read_csv, read_tsv, read_delim, read_fwf, read_table...
│   ├── writers.r                       # write_csv, write_tsv, write_delim...
│   ├── parsing.r                       # parse_*, col_*, locale, problems
│   └── helpers.r                       # type_convert, melt_csv, etc.
│
├── purrr/
│   ├── __init__.r
│   ├── map.r                           # map, map2, pmap, imap, map_*, walk*
│   ├── reduce.r                        # reduce, accumulate, reduce2...
│   ├── predicate.r                     # keep, discard, compact, every, some, none, detect...
│   ├── pluck.r                         # pluck, chuck, pluck_depth, assign_in...
│   ├── modify.r                        # modify, modify_if, modify_at, modify_depth...
│   └── rate.r                          # slowly, insistently, rate_* (optional)
│
├── stringr/
│   ├── __init__.r
│   ├── detect.r                        # detect, which, subset, starts, ends
│   ├── match.r                         # extract, match, locate, count
│   ├── mutate.r                        # replace, replace_all, remove, sub
│   ├── split.r                         # split, split_i, split_1
│   ├── pad_trim.r                      # pad, trim, trunc, wrap
│   ├── case.r                          # to_lower, to_upper, to_title, to_sentence
│   └── helpers.r                       # c, length, order, sort, regex, fixed...
│
├── forcats/
│   ├── __init__.r
│   ├── reorder.r                       # reorder, reorder2, infreq, inorder...
│   ├── recode.r                        # recode, collapse, lump*, other
│   ├── level.r                         # relevel, expand, drop, unify
│   └── helpers.r                       # as_factor, count, match, relabel...
│
└── lubridate/
    ├── __init__.r
    ├── parse.r                         # ymd, mdy, dmy, ymd_hms, parse_date_time...
    ├── accessors.r                     # year, month, day, hour, minute, second, wday, yday...
    ├── arithmetic.r                    # +, -, %m+%, %m-%, add_with_rollback...
    ├── periods.r                       # years, months, weeks, days, hours... (duration/period)
    ├── intervals.r                     # interval, int_start, int_end, int_length, %within%
    ├── timezones.r                     # with_tz, force_tz, OlsonNames...
    └── helpers.r                       # today, now, as_date, as_datetime, stamp...

And if I am going to need dplyr from tidyverse, for example, I simply would like to declare the imports through the following:

box::use(
    tidyverse/dplyr,                          # 1
    tidyverse/dplyr/verbs[...],               # 2
    tidyverse/dplyr/helpers/select[...]       # 3
)
  1. Here, I would want to import the whole dplyr module without attaching names, unlike the usual library(dplyr) in R.
  2. When I want all the main dplyr verbs attached to the current environment, without attaching everything else in dplyr, I do this.
  3. The same as 2, but for the names exported by the helpers/select.r submodule.

I prefer this because you no longer need to write prefixes while naming the functions, which usually to avoid namespace clashing, the workaround many packages use (such as fct_reorder() and fct_relevel() from forcats. Though I admit this type of declaration is a bit verbose. Declare the names without prefixes, import the module without attaching its names, and give it an alias:

box::use(fct = tidyverse/forcats)

set.seed(123)
x = sample(letters[1:5], 50, replace = TRUE) |> 
    factor(levels = letters[1:5])
fct$count(x)
fct$unique(x)

3.1 To get started

Assuming you are on the existing directory, run one of the following:

  1. Without a source code directory:

    baler init
  2. With an existing source code directory:

    baler init --src <directory-name>

baler init always writes the metadata file, baler.toml, which is similar to DESCRIPTION in a CRAN-style R package.

3.2 Declaring dependencies

baler.toml, under [dependencies] and [dependencies.baler] blocks, is where R packages and external box-bale modules, respectively. Version constraints use the same style you would see in Python packages or Rust’s Cargo.

[dependencies]
dplyr = ">=1.1.0"
tidyr = "*"

3.3 Installing modules

There are a few ways to install a box-bale module. To begin with, let me provide you some warning:

baler install <name-of-the-module> is the ordinary way to install a module, but it is reserved for modules hosted in a registry (think of CRAN). The registry for box-bale modules has not been built yet, so use the alternatives below.

  1. When you want to install a box-bale module from a local path, flag it with --path, and you can now simply install the module from a directory or a tarball archive.

    baler install --path .
    baler install --path <name-of-the-module>_<version>.tar.gz
    baler install --path . --install-deps
  2. How installing a module directly from a GitHub repo works is what I intended initially when making carrier. Pass it down with --git and some little options where those modules you wanted to install lived, otherwise the argument you supplied will be the root directory of that repo.

    baler install --git <GitHub URL> 
    baler install --git <GitHub URL> --branch <Git Branch>
    baler install --git <GitHub URL> --tag <GitHub tag>
    baler install --git <GitHub URL> --module-dir <dir>
    baler install --git <GitHub URL> --module-dir <dir> --tag <GitHub tag>
  3. When you flag it with --url instead, the link is directed where the archived box-bale modules lived. This option is added intentionally to allow archived sources to be retrieved.

    baler install --url \ 
        <url.tar.gz>

An installed module behaves like a package, so you load it with how you load packages with box::use() as usual:

box::use(
    module_name,
    some_alias = module_name, 
    module_name[some_function],
    module_name[alias_fn = some_function]
)

3.4 Locking dependencies

Like pip freeze or uv lock, {baler} can record the exact resolved dependency tree in baler.lock. Locking is opt-in by presence: if baler.lock exists, the installation will look up here, otherwise baler.toml is used as the basis. Record the dependency tree by running one of the following from the module directory:

baler lock                      # The directory defaults to `.`
baler lock --with-rver          # Also records the R version
baler lock --update             # Re-resolves the dependency tree and updates the lockfile

Commit baler.lock to version control, so everyone on the project gets the same dependency structure.

4 Lazy Imports

I submitted a GitHub PR for this feature last October 12, 2026. By default, box::use() loads everything it is given at the moment it runs. If a module imports a heavy package that only one rarely used function needs, you pay the loading cost on every run, even when that function is never called. Lazy imports defer that cost until the name is first used. The feature is submitted as a pull request to upstream box, and you can already try it (see below).

Use lazy() and take the declared import inside of it to make it lazy, or otherwise, imports without it behave as before:

box::use(
    lazy(dplyr),
    tidyr
)

Here, dplyr is only loaded when something from it is first accessed, while tidyr is loaded immediately. This is the same idea as the lazy soft keyword from PEP 810, which Python 3.15 now ships:

lazy import json
import os

The prefix works on everything you can pass to box::use(): packages, local modules, submodules, and modules installed with {baler}.

4.1 How it works

Let’s start with a toy example. Suppose you write a module, heavy.r, that announces itself when it is evaluated:

# heavy.r
message("[heavy] module is loading")

#' @export
double = function(x) {
    x * 2
}

Then another module, main.r, imports it lazily:

# main.r
box::use(
    lazy(./heavy)
)

message("[main] imports declared")
print(heavy$double(21))
message("[main] done")

Running Rscript main.r then prints:

[main] imports declared
[heavy] module is loading
[1] 42
[main] done

box::use() binds the name heavy right away, but heavy.r is not evaluated yet during import time. The module loads at the first access, heavy$double(), which is why [heavy] module is loading shows up between the two [main] messages. Drop the lazy() usage and now the order flips, because the module loads while box::use() runs:

[heavy] module is loading
[main] imports declared
[1] 42
[main] done

A lazy import that is never touched is never loaded. If main.r declares lazy(./heavy) but never uses heavy, the [heavy] message never appears.

Lazy imports also work with an attach list. In box::use(lazy(./heavy[double])), the name double is bound immediately, and heavy.r is evaluated the first time double is used:

box::use(lazy(./heavy[double]))

message("[main] imports declared")
print(double(21))
[main] imports declared
[heavy] module is loading
[1] 42

This example needs the fork from Try it.

Warning

A lazy import cannot use the [...] wildcard, because attaching every export requires loading the package to know what they are. Python has the same restriction for lazy from module import *.

4.2 Try it

The lazy imports pull request has been submitted to box and is awaiting merge. Until then, you can try it from my fork:

# install.packages('pak')
pak::pak("joshuamarie/box@feature/lazy-imports")

5 Not exactly new but astral

Not exactly new, but worth showing with {baler} and box together: three things that other languages made routine, now available for R modules.

5.1 Writing native compiled code

A module can ship compiled code, such as Rcpp. With {baler}, you declare it in baler.toml, and baler install builds and caches the compiled code automatically, with no manual steps:

[compiled-code]
# path = ["src/"]
binary = true
keep_source = true

[compiled-code.build-deps]
Rcpp = ">=1.1.0"
RcppEigen = "*"
RcppParallel = ">=6.0.0"
BH = "*"

build-deps lists the packages needed to compile the code. Since the build is cached, users do not recompile on every install. As with any Rcpp code, a compiler toolchain is still needed on the machine that builds it (Rtools on Windows).

5.2 The if __name__ == '__main__' idiom synonym

In Python, this idiom lets a file act as both an importable module and a runnable script. Save the following code below as run.py:

from utils import clean

def main():
    return clean()

if __name__ == "__main__":
    main()

box has an equivalent. It uses box::name() and returns NULL rather than '__main__' when a file runs as a script, and the module name when it is imported (save this as run.r:

box::use(./utils[clean])

main = function() {
    clean()
}

if (is.null(box::name())) {
    main()
}

Run it with Rscript path/to/run.r and main() executes. Import it from another module with box::use(./run[main]) and nothing runs until you call it.

5.3 Testing modules

It doesn’t matter what R packages you used, you are free to write unit tests for modules. The most popular one is the testthat. A test file imports the module under test with box::use(), then calls its functions like any other code. Suppose the project looks like this:

my_project/
├── R/
│   ├── __init__.r
│   └── stats_utils.r
└── tests/
    ├── __init__.r
    └── test-stats_utils.r

Our example module under test, R/stats_utils.r, exports a coefficient of variation. A module only sees base R by default, so sd() has to be imported from {stats}:

box::use(
    stats[sd]
)

cv = function(x) {
    sd(x) / mean(x) * 100
}

The __init__.r file contains the attached testthat package — all the names are now used throughout tests/ — and the .on_load(ns) hook, in which when tests/ module is loaded and then the following code:

box::use(testthat[...])

.on_load = function (ns) {
    test_dir(box::file(), reporter = 'progress')
}

box::export()

All the tests you wrote are executed. The alternative way is to place

if (is.null(box::name())) {
    box::use(./tests)
}

at the bottom of R/stats_utils.r, so that when you execute this module by running Rscript ./R/stats_utils.r, all the tests will be run at once.

The test file, tests/test-stats_utils.r, imports that module:

box::use(
    ../R/stats_utils,
    stats[rnorm, rpois]
)

test_that("cv is zero for constant input", {
    expect_equal(stats_utils$cv(c(2, 2, 2)), 0)
})

test_that("cv is working for all numeric data but not working for non-numeric data", {
    set.seed(123)
    x = rnorm(100, 0.97, 2)
    y = rpois(100, 3.5)
    groups = sample(letters[1:5], size = 50, replace = TRUE)
    
    expect_no_error(stats_utils$cv(x))
    expect_no_error(stats_utils$cv(y))
    expect_error(stats_utils$cv(groups))
})

The path ../R/stats_utils is relative to the test file, not to your working directory, so the test runs the same from anywhere. As what said above, the execution of the tests is via loading the tests/ module, or by running Rscript ./R/stats_utils.r in case that the idiom exists, but the another alternative way where you only want to execute this test file. Here’s the following code you need to place at the bottom of R/stats_utils.r script:

if (is.null(box::name())) {
    testthat::test_file("tests/test-stats_utils.r")
}

References