vadr (version 0.01)

put: Modify part of a value.

Description

The macro put provides syntax for modifying part of an object in a functional context (i.e. creating a modified value without necessarily binding the result to a name.) Unlike <-, the value of the expression is the modified object, not the value that was injected. This is particularly useful in combination with 'chain.'

alter takes the selected subset of it, then filters it through additional functions in the manner of chain, then replaces the subset with the result, returning the modified object.

inject takes the entire object, filters it through a chain, then places the result in the specified subset.

Usage

put(it, subset, value)
alter(it, subset, ...)
inject(it, subset, ...)

Arguments

...
A chain of code transformations.
it
A value.
subset
A subassignment target expression; this is interpreted literally if the symbol it is used, otherwise it is injected as far down the leftmost arguments of the expression as possible. (Thus names is interpreted as names(it), and names[1] as names(it)[1].)
value
The value to assign

Value

The modified value.

Details

Normal subassignment in R is effectively a macro, one which turns a statement like

names(x)[1] <- "head"

into something like

x <- `names<-`(x, `[<-`(names(x), "head", 1))

However even this explanation is misleading, because the value returned from a subassignment is the value applied, not the value assigned. Consider if you wanted to call a function with a modification of an existing value:

do_something(names(x)[1] <- "head")

Aside from changing the value of x this actually doesn't pass the value to do_something, but rather performs the equivalent of do_something("head").

In this situation, using put, one can write:

do_something(put(x, names[1], "head"))

codeput and friends are particularly useful in conjunction with chain.

x %<~% alter(names[5],="" toupper)<="" code=""> is equivalent to:

names(x)[5] <- toupper(names(x)[5])

x <- inject(1:10, names, letters[.], toupper) is equivalent to:

x <- 1:10; names(x) <- toupper(letters[x])

See Also

chain

Examples

Run this code
put(1:10, names, letters[1:10])
x <- 1:10
put(x, it[1], 4)
put(x, names[4], 'a')
x #x is unchanged
x <- alter(structure(1:10, names=letters[1:10]), names)
y <- alter(x, names[5], toupper, str_dup(3))
x <- inject(1:10, names[1:5], letters[.], rev)

Run the code above in your browser using DataCamp Workspace