寻找一种在引用的语言对象上使用 substitute 作为表达式的方法。
substitute
期望在expr
得到懒惰的表达。
目标是替换expr.template
中的.expr
,这是一种基于元数据动态生成的语言对象。
## data
expr = quote(x <- f(10))
expr.template = quote(g(.expr, flag = TRUE))
## expected output
quote(g(x <- f(10), flag = TRUE))
#g(x <- f(10), flag = TRUE)
## current workaround
h = function(expr, expr.template){
eval(substitute(
substitute(
.expr.template,
list(.expr = expr)
),
list(.expr.template = expr.template)
))
}
h(expr = expr, expr.template = expr.template)
#g(x <- f(10), flag = TRUE)
因此,如果没有更多规范的方法来处理它,我会感到惊讶。首选碱性R解决方案。
使用 do.call
:
do.call("substitute", list(expr.template, list(.expr = expr)))
## g(x <- f(10), flag = TRUE)