• Stars
    star
    737
  • Rank 61,490 (Top 2 %)
  • Language
    R
  • License
    MIT License
  • Created over 11 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Write reusable, composable and modular R code

box

Write Reusable, Composable and Modular R Code

CRAN status badge R-universe status badge

📦 Installation

‘box’ can be installed from CRAN:

install.packages('box')

Alternatively, the current development version can be installed from R-universe (note that it cannot be installed directly from GitHub!):

install.packages('box', repos = 'https://klmr.r-universe.dev')

🥜 Usage in a nutshell

‘box’ allows organising R code in a more modular way, via two mechanisms:

  1. It enables writing modular code by treating files and folders of R code as independent (potentially nested) modules, without requiring the user to wrap reusable code into packages.
  2. It provides a new syntax to import reusable code (both from packages and modules) that is more powerful and less error-prone than library by allowing explicit control over what names to import, and by restricting the scope of the import.

Reusable code modules

Code doesn’t have to be wrapped into an R package to be reusable. With ‘box’, regular R files are reusable R modules that can be used elsewhere. Just put the export directive #' @export in front of names that should be exported, e.g.:

#' @export
hello = function (name) {
    message('Hello, ', name, '!')
}

#' @export
bye = function (name) {
    message('Goodbye ', name, '!')
}

Existing R scripts without @export directives can also be used as modules. In that case, all names inside the file will be exported, unless they start with a dot (.).

Such modules can be stored in a central module search path (configured via options('box.path')) analogous to the R package library, or locally in individual projects. Let’s assume the module we just defined is stored in a file hello_world.r inside a directory mod, which is inside the module search path. Then the following code imports and uses it:

box::use(mod/hello_world)

hello_world$hello('Ross')
#> Hello, Ross!

Modules are a lot like packages. But they are easier to write and use (often without requiring any set-up), and they offer some other nice features that set them apart from packages (such as the ability to be nested hierarchically).

For more information on writing modules refer to the Get started vignette.

Loading code

box::use provides a universal import declaration. It works for packages just as well as for modules. In fact, ‘box’ completely replaces the base R library and require functions. box::use is more explicit, more flexible, and less error-prone than library. At its simplest, it provides a direct replacement:

Instead of

library(ggplot2)

You’d write

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

This tells R to import the ‘ggplot2’ package, and to make all its exported names available (i.e. to “attach” them) — just like library. For this purpose, ... acts as a wildcard to denote “all exported names”. However, attaching everything is generally discouraged (hence why it needs to be done explicitly rather than happening implicitly), since it leads to name clashes, and makes it harder to retrace which names belong to what packages.

Instead, we can also instruct box::use to not attach any names when loading a package — or to just attach a few. Or we can tell it to attach names under an alias, and we can also give the package itself an alias.

The following box::use declaration illustrates these different cases:

box::use(
    purrr,                          # 1
    tbl = tibble,                   # 2
    dplyr = dplyr[filter, select],  # 3
    stats[st_filter = filter, ...]  # 4
)

Users of Python, JavaScript, Rust and many other programming languages will find this use declaration familiar (even if the syntax differs):

The code

  1. imports the package ‘purrr’ (but does not attach any of its names);
  2. creates an alias tbl for the imported ‘tibble’ package (but does not attach any of its names);
  3. imports the package ‘dplyr’ and additionally attaches the names dplyr::filter and dplyr::select; and
  4. attaches all exported names from ‘stats’, but uses the local alias st_filter for the name stats::filter.

Of the four packages loaded in the code above, only ‘purrr’, ‘tibble’ and ‘dplyr’ are made available by name (as purrr, tbl and dplyr, respectively), and we can use their exports via the $ operator, e.g. purrr$map or tbl$glimpse. Although we’ve also loaded ‘stats’, we did not create a local name for the package itself, we only attached its exported names.

Thanks to aliases, we can safely use functions with the same name from multiple packages without conflict: in the above, st_filter refers to the filter function from the ‘stats’ package; by contrast, plain filter refers to the ‘dplyr’ function. Alternatively, we could also explicitly qualify the package alias, and write dplyr$filter.

Furthermore, unlike with library, the effects of box::use are restricted to the current scope: we can load and attach names inside a function, and this will not affect the calling scope (or elsewhere). So importing code happens locally, and functions which load packages no longer cause global side effects:

log = function (msg) {
    box::use(glue[glue])
    # We can now use `glue` inside the function:
    message(glue('[LOG MESSAGE] {msg}'))
}

log('test')
#> [LOG MESSAGE] test

# … But `glue` remains undefined in the outer scope:
glue('test')
#> Error in glue("test"): could not find function "glue"

This makes it easy to encapsulate code with external dependencies without creating unintentional, far-reaching side effects.

‘box’ itself is never loaded via library. Instead, its functionality is always used explicitly via box::use.

Getting help

If you encounter a bug or have a feature request, please post an issue report on GitHub. For general questions, posting on Stack Overflow, tagged as r-box, is also an option. Finally, there’s a GitHub Discussions board at your disposal.

Why ‘box’?

‘box’ makes it drastically easier to write reusable code: instead of needing to create a package, each R code file is already a module which can be imported using box::use. Modules can also be nested inside directories, such that self-contained projects can be easily split into separate or interdependent submodules.

To make code reuse more scalable for larger projects, ‘box’ promotes the opposite philosophy of what’s common in R: some notable packages export and attach many hundreds and, in at least one notable case, over a thousand names. This works adequately for small-ish analysis scripts but breaks down for even moderately large software projects because it makes it non-obvious where names are imported from, and increases the risk of name clashes.

To make code more explicit, readable and maintainable, software engineering best practices encourage limiting both the scope of names, as well as the number of names available in each scope.

For instance, best practice in Python is to never use the equivalent of library(pkg) (i.e. from pkg import *). Instead, Python strongly encourages using import pkg or from pkg import a, few, symbols, which correspond to box::use(pkg) and box::use(pkg[a, few, symbols]), respectively. The same is true in many other languages, e.g. C++, Rust and Perl. Some languages (e.g. JavaScript) are even stricter: they don’t support unqualified wildcard imports at all.

The Zen of Python puts this rule succinctly:

Explicit is better than implicit.

More Repositories

1

named-operator

Named operators for C++
C++
487
star
2

cpp11-range

Range-based for loops to iterate over a range of numbers or values
C++
304
star
3

thesis

My PhD thesis, “Investigating the link between tRNA and mRNA abundance in mammals”
TeX
38
star
4

lisp.cpp

Minimal Lisp implementation in C++, inspired by “lispy”
C++
37
star
5

decorator

R function decorators
R
33
star
6

multifunction

A multicast function type for C++
C++
27
star
7

minimappr

Code minimaps for R
R
19
star
8

hyperlight

Automatically exported from code.google.com/p/hyperlight
PHP
16
star
9

fun

Module for functional programming in R
R
16
star
10

sys

Easily create reusable command line scripts with R
R
13
star
11

example-r-analysis

An example for an R analysis workflow using a Makefile, shell scripts and Knitr
R
12
star
12

trna

tRNA gene regulation downstream analysis
R
8
star
13

cv

Resume
TeX
6
star
14

unpack

Vector unpack assignment syntax for R
R
5
star
15

math-art

R
4
star
16

streampunk

Compiler for a pipe-based stream language to construct complex pipelines
C++
4
star
17

knitr-example

An example of a genomics analysis using knitr
4
star
18

rcane

Miscellaneous R tools that I haven’t had time yet to properly integrate. (deprecated and unmaintained)
R
3
star
19

modules

An alternative module system for R
R
3
star
20

parser-combinators

Parser combinators in R
R
2
star
21

system-setup

Bootstrap a usable system configuration for OS X
Shell
2
star
22

vim-snakemake

Snakemake Vim definitions, copied from https://bitbucket.org/snakemake/snakemake/
Vim Script
2
star
23

.files

My dotfiles repository
Shell
2
star
24

klmr.github.io

My website
JavaScript
2
star
25

switch-r

R version switcher for macOS
Shell
2
star
26

cpp11-raw-ptr

A raw pointer type for C++11
C++
2
star
27

te

Map, quantify and analyse transposable element expression
Makefile
2
star
28

ggplots

Some (different, better) defaults for ggplot2
R
2
star
29

trna-chip-pipeline

Upstream ChIP-seq analysis pipeline for tRNA data
Python
2
star
30

rnaseq-norm

Presentation slides about RNA-seq normalisation methods
Makefile
1
star
31

pichip

Makefile
1
star
32

codons

Analysis of adaptation of translation efficiency by means of codon–anticodon selection
R
1
star
33

bog-2015-poster

Biology of Genomes 2015 poster
PostScript
1
star
34

aka

R
1
star
35

roxydoxy

R
1
star
36

r-dict

R
1
star
37

poly-u

R
1
star
38

royal-jelly

R
1
star