Decompose and Recompose Functions

Install

remotes::install_github("ropenscilabs/astr")
library("astr")

decompose

a simple function

foo <- function(x) {
  x + 1
}
foo(5)
#> [1] 6

decompose the function

df <- ast_decompose(foo)
df
#> { fxn: foo }
#> function (x)
#> {
#>     x + 1
#> }
class(df)
#> [1] "ast"        "data.frame"

modify

modify an aspect of the function

out <- ast_modify(df, from = "+", to = "-")
out
#> { fxn: foo }
#> function (x)
#> {
#>     x - 1
#> }

recompose

ast_recompose(out)
#> [1] "function (x)\n{\n    x - 1\n}"
ex <- ast_recompose(out, as_expr = TRUE)
eval(ex)(5)
#> [1] 4

Meta