Named Map Builder

2022-01-26

“named map builder” is an operator written as “:=”. Named map builder is a very simple bit of code that performs a very simple task: it adds names to vectors or lists (making them work more like maps).

Here are some examples:

library("wrapr")

'a' := 5
## a
## 5
c('a' := 5, 'b' := 6)
## a b
## 5 6
c('a', 'b') := c(5, 6)
## a b
## 5 6

The left-side argument of the := operator is called “the names”, and the right-side argument is called “the values”. The := operators returns the values with the names set to names.

:= is a left-over assignment operator in R. It is part of the syntax, but by default not defined.

data.table has long used := to denote “in-place assignment” as in the following.

library("data.table")

data.table(x = 1)[, y := x + 1][]
#    x y
# 1: 1 2

dplyr later adopted the := notation as this allows for substitution on the left-hand sides of assignments. wrapr::qc() uses the := for the same purpose.

A key use of the named map builder is the following:

:= <- wrapr:::= # in case data.tables "catch calls" definition is active

key = 'keycode'
key := 'value'
## keycode
## "value"

Notice the value inside the variable key was used as the array name, this differs from what is easily done with R’s native c(key = 'value') style notation.

help(:=, package = 'wrapr')