ReplaceInExpression: Replace as sub-expression isnide an expression

Description Usage Arguments Details Value References Examples

Description

Replace every subexpression equal to or starting with what in expr. Replacement is performed by passing the whole subexpression to replacer.func, which should be a function(x, ...), where x is the expression and return the desirable expression.

Usage

1
ReplaceInExpression(expr, what, replacer.func, ...)

Arguments

expr

An expression.

what

A backquoted expression to find in expr.

replacer.func

A function(x, ...) to process the subexpression.

...

Other parameters passed to replacer.func.

Details

This function was designed to be used as a runtime processing tool for grammar generated expression. This allows the user to modify the resulting expression on the fly based on runtime variables, without including them in the grammar. See examples section.

Value

An expression

References

See http://adv-r.had.co.nz/Expressions.html by Hadley Wickham.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
expr = expression(function(x) {
    cbind(f1(x),
          f2(x),
          g3(y))
})
expr
ReplaceInExpression(expr, bquote(f2), function(x) {NULL})
ReplaceInExpression(expr, bquote(f2), function(x) {bquote(f2(y))})
ReplaceInExpression(expr, bquote(g3), function(x) {bquote(f3(x))})
ReplaceInExpression(expr, bquote(g3), function(x, b) {if (b > 1) x else NULL}, b = 0)
ReplaceInExpression(expr, bquote(g3), function(x, b) {if (b > 1) x else NULL}, b = 2)

Example output

expression(function(x) {
    cbind(f1(x), f2(x), g3(y))
})
expression(function(x) {
    cbind(f1(x), NULL, g3(y))
})
expression(function(x) {
    cbind(f1(x), f2(y), g3(y))
})
expression(function(x) {
    cbind(f1(x), f2(x), f3(x))
})
expression(function(x) {
    cbind(f1(x), f2(x), NULL)
})
expression(function(x) {
    cbind(f1(x), f2(x), g3(y))
})

gramEvol documentation built on July 18, 2020, 5:07 p.m.