ast_modify: Modify an R function

View source: R/ast_modify.R

ast_modifyR Documentation

Modify an R function

Description

Modify an R function

Usage

ast_modify(x, from, to, if_many = "random", no_match = stop)

Arguments

x

an object of class ast

from

(character) character string to replace. note that we look for an exact match

to

(character) character string to put in place of from

if_many

(character) if multiple matches to the from parameter input, should we randomly select one to replace, replace the first instance, or replace all? one of: first, all, random

no_match

(function) how to deal with no matches. by default we stop(), but you can set to warning() or message()

Details

we check that the from input has a match in the function data, if not, we fail out

Value

same as the input, an object of class ast, but modified

Examples

foo <- function(x) {
  x + 1
}
foo(5)

# decompose the function
df <- ast_decompose(foo)
df
data.frame(df)
attr(df, "expr")

# modify an aspect of the function
out <- ast_modify(x = df, from = "+", to = "-")
out
class(out)
attributes(out)
data.frame(out)
attr(out, "expr")

# more examples
bar <- function(x) x / 6
(z <- ast_decompose(bar))
ast_modify(z, from = "/", to = "*")

# to get the new function, pass through ast_recompose
b <- ast_modify(z, from = "/", to = "*")
newbar <- ast_recompose(b, TRUE)
bar(7)
eval(newbar)(7)

# multiple from matches
foo <- function(x) {
  w <- x + 1
  w + 5
}
foo(1)
x <- ast_decompose(foo)
(w <- ast_modify(x, "+", "-"))
eval(ast_recompose(w, TRUE))(1)

# if_many options
ast_modify(x, "+", "-", if_many = "random")
ast_modify(x, "+", "-", if_many = "random")
ast_modify(x, "+", "-", if_many = "random")
ast_modify(x, "+", "-", if_many = "first")
ast_modify(x, "+", "-", if_many = "all")

sckott/astr documentation built on Nov. 12, 2024, 4:19 p.m.