Recursively modify a language object

modify_lang(x, f, ...)

Arguments

x

object to modify: should be a call, expression, function or list of the above.

f

function to apply to leaves

...

other arguments passed to f

Examples

a_to_b <- function(x) {
  if (is.name(x) && identical(x, quote(a))) return(quote(b))
  x
}
examples <- list(
  quote(a <- 5),
  alist(a = 1, c = a),
  function(a = 1) a * 10,
  expression(a <- 1, a, f(a), f(a = a))
)
modify_lang(examples, a_to_b)
#> [[1]]
#> b <- 5
#> 
#> [[2]]
#> [[2]]$a
#> [1] 1
#> 
#> [[2]]$c
#> b
#> 
#> 
#> [[3]]
#> function (a = 1) 
#> b * 10
#> <environment: 0x58b584d250d8>
#> 
#> [[4]]
#> expression(b <- 1, b, f(b), f(a = b))
#> 
# Modifies all objects called a, but doesn't modify arguments named a