dub

Unpacking Assignment for Lists via Pattern Matching


Keywords
pattern-matching, r, unpacking-assignment
License
MIT

Documentation

Travis build status Coverage status CRAN_Status_Badge

dub

dub is a small, single-purpose R package for unpacking assignment: it provides an operator %<<-% that enables you to assign (nested) components of a list (or vector) to names via pattern matching. The pattern matching syntax mirrors the semantics of list(). Think of the “dub(ble) arrow” <<- as a pictograph representing multiple <-’s.

library(dub)

(one : two : three) %<<-% 1:3
one
#> [1] 1
two
#> [1] 2
three
#> [1] 3

(x) %<<-% list(list("x"))
((y)) %<<-% list(list("y"))
x
#> [[1]]
#> [1] "x"
y
#> [1] "y"

(u : (v : w)) %<<-% list(1, list(2, 3:4))
u
#> [1] 1
v
#> [1] 2
w
#> [1] 3 4

# Use . to drop specific components, ... to drop greedily (the _ in Haskell)
(. : width : ... : species) %<<-% iris
head(width)
#> [1] 3.5 3.0 3.2 3.1 3.6 3.9
head(species)
#> [1] setosa setosa setosa setosa setosa setosa
#> Levels: setosa versicolor virginica

More details and examples are in the package documentation (?`%<<-%` ).

Installation

Install from CRAN:

install.packages("dub")

Alternatively, install the development version from GitHub:

# install.packages("devtools")
devtools::install_github("egnha/dub")

Prior art

Unpacking/multiple assignment appears in other languages (e.g., Python, JavaScript, Clojure). While R has no such feature, using a custom operator to do this has long been a folklore method. To my knowledge, the earliest implementation is by Gabor Grothendieck (2004), cf. list in the gsubfn package.

If you need specialized forms of “destructured” assignment, I recommend the zeallot package by Nate Teetor.

License

MIT Copyright © 2018 Eugene Ha