Skip to content
/ dub Public

Unpacking assignment via pattern matching

License

Unknown, MIT licenses found

Licenses found

Unknown
LICENSE
MIT
LICENSE.md
Notifications You must be signed in to change notification settings

egnha/dub

Repository files navigation

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

About

Unpacking assignment via pattern matching

Topics

Resources

License

Unknown, MIT licenses found

Licenses found

Unknown
LICENSE
MIT
LICENSE.md

Stars

Watchers

Forks

Packages

No packages published

Languages