Modify an R function
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 towarning()
ormessage()
Examples
foo <- function(x) {
x + 1
}
foo(5)
#> [1] 6
# decompose the function
df <- ast_decompose(foo)
#> Error in as_string(x): Can't convert a logical vector to a string.
df
#> function (x, df1, df2, ncp, log = FALSE)
#> {
#> if (missing(ncp))
#> .Call(C_df, x, df1, df2, log)
#> else .Call(C_dnf, x, df1, df2, ncp, log)
#> }
#> <bytecode: 0x564bf3967008>
#> <environment: namespace:stats>
data.frame(df)
#> Error in as.data.frame.default(x[[i]], optional = TRUE): cannot coerce class ‘"function"’ to a data.frame
attr(df, "expr")
#> NULL
# modify an aspect of the function
out <- ast_modify(x = df, from = "+", to = "-")
#> Error: x must be of class ast
out
#> Error: object 'out' not found
class(out)
#> Error: object 'out' not found
attributes(out)
#> Error: object 'out' not found
data.frame(out)
#> Error: object 'out' not found
attr(out, "expr")
#> Error: object 'out' not found
# more examples
bar <- function(x) x / 6
(z <- ast_decompose(bar))
#> Error in as_string(x): Can't convert a logical vector to a string.
ast_modify(z, from = "/", to = "*")
#> Error: object 'z' not found
# to get the new function, pass through ast_recompose
b <- ast_modify(z, from = "/", to = "*")
#> Error: object 'z' not found
newbar <- ast_recompose(b, TRUE)
#> Error: object 'b' not found
bar(7)
#> [1] 1.166667
eval(newbar)(7)
#> Error: object 'newbar' not found
# multiple from matches
foo <- function(x) {
w <- x + 1
w + 5
}
foo(1)
#> [1] 7
x <- ast_decompose(foo)
#> Error in as_string(x): Can't convert a logical vector to a string.
(w <- ast_modify(x, "+", "-"))
#> Error: object 'x' not found
eval(ast_recompose(w, TRUE))(1)
#> Error: object 'w' not found
# if_many options
ast_modify(x, "+", "-", if_many = "random")
#> Error: object 'x' not found
ast_modify(x, "+", "-", if_many = "random")
#> Error: object 'x' not found
ast_modify(x, "+", "-", if_many = "random")
#> Error: object 'x' not found
ast_modify(x, "+", "-", if_many = "first")
#> Error: object 'x' not found
ast_modify(x, "+", "-", if_many = "all")
#> Error: object 'x' not found