dub

Unpacking assignment via pattern matching

OTHER License

Downloads
161
Stars
10
Committers
1

output: github_document

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

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
two
three

(x) %<<-% list(list("x"))
((y)) %<<-% list(list("y"))
x
y

(u : (v : w)) %<<-% list(1, list(2, 3:4))
u
v
w

# Use . to drop specific components, ... to drop greedily (the _ in Haskell)
(. : width : ... : species) %<<-% iris
head(width)
head(species)

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

Installation

Install from CRAN:

install.packages("dub")
```

Alternatively, install the development version from GitHub:

```{r gh-installation, eval = FALSE}
# install.packages("devtools")
devtools::install_github("egnha/dub")
```

## Prior art

Unpacking/multiple assignment appears in other languages (e.g., [Python](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences), [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), [Clojure](https://clojure.org/guides/destructuring)). 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](https://stat.ethz.ch/pipermail/r-help/2004-June/053343.html) (2004), cf. `list` in the [gsubfn](https://cran.r-project.org/package=gsubfn) package.

If you need specialized forms of "destructured" assignment, I recommend the
[zeallot](https://github.com/nteetor/zeallot) package by [Nate
Teetor](https://github.com/nteetor).

## License

MIT Copyright © 2018 [Eugene Ha](https://github.com/egnha)