ast_modify | R Documentation |
Modify an R function
ast_modify(x, from, to, if_many = "random", no_match = stop)
x |
an object of class |
from |
(character) character string to replace. note that we look for an exact match |
to |
(character) character string to put in place of |
if_many |
(character) if multiple matches to the |
no_match |
(function) how to deal with no matches. by default we
|
we check that the from
input has a match in the function
data, if not, we fail out
same as the input, an object of class ast
, but modified
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")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.