bquote
函数允许计算表达式中包含的部分.()
称呼。例如,
a <- 2
b <- 100
bquote(.(2 * a) * x + .(log10(b)))
会回来
4 * x + 2
我想重写这个函数来评估除了里面的东西之外的所有东西.()
称呼。这是期望的行为:
a <- 2
b <- 100
bquote(2 * a * .(x) + log10(b))
> 4 * x + 2
我明白,要做到这一点,我必须仔细检查抽象语法树 http://adv-r.had.co.nz/Expressions.html#structure-of-expressions并评估早午餐,无需.()
调用它们,但我无法处理所有这些递归。
你能帮我写一个这样的函数吗?
subst
将替换除 .(...) 和 中的变量之外的所有变量simplify
函数将简化没有变量的子树——如果不需要简化,则省略简化部分。没有使用任何包。
subst <- function(e) {
if (typeof(e) == "language") {
if (identical(e[[1]], as.name("."))) e[[2]]
else {
if (length(e) > 1) e[-1] <- lapply(as.list(e[-1]), subst)
e
}
} else {
eval(e)
}
}
simplify <- function(e) {
if (typeof(e) == "language") {
if (length(all.vars(e))) {
if (length(e) > 1) {
e[-1] <- lapply(as.list(e[-1]), simplify)
e
} else e
} else eval(e)
} else e
}
inverse_bquote <- function(x, SIMPLIFY = TRUE) {
result <- subst(substitute(x))
if (SIMPLIFY) simplify(result) else result
}
现在测试一下。
a <- 2
b <- 100
inverse_bquote(2 * a * .(x) + log10(b))
## 4 * x + 2
# without simplification
inverse_bquote(2 * a * .(x) + log10(b), SIMPLIFY = FALSE)
## 2 * 2 * x + log10(100)
Update:添加了简化。使其成为可选的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)