我正在尝试使用 NSE 构建一个公式,以便我可以轻松地在列中进行管道传输。以下是我想要的用例:
df %>% make_formula(col1, col2, col3)
[1] "col1 ~ col2 + col3"
我首先做了这个功能:
varstring <- function(...) {
as.character(match.call()[-1])
}
这对于单个对象或多个对象都非常有效:
varstring(col)
[1] "col"
varstring(col1, col2, col3)
[1] "col1" "col2" "col3"
我创建函数来创建接下来的公式:
formula <- function(df, col, ...) {
group <- varstring(col)
vars <- varstring(...)
paste(group,"~", paste(vars, collapse = " + "), sep = " ")
}
但是,函数调用 formula(df, col, col1, col2, col3)
会生成 [1] "group ~ ..1 + ..2 + ..3"
.
我知道该公式实际上是在评估 varstring(group)
和 varstring(...)
而不是像我那样实际替换用户提供的对象进行评估也喜欢。但我不知道如何使这项工作按预期进行。
最佳答案
您可以使用reduce()
将任意数量的参数与二元函数连接起来
make_formula <- function(lhs, ..., op = "+") {
lhs <- ensym(lhs)
args <- ensyms(...)
n <- length(args)
if (n == 0) {
rhs <- 1
} else if (n == 1) {
rhs <- args[[1]]
} else {
rhs <- purrr::reduce(args, function(out, new) call(op, out, new))
}
# Don't forget to forward the caller environment
new_formula(lhs, rhs, env = caller_env())
}
make_formula(disp)
#> disp ~ 1
make_formula(disp, cyl)
#> disp ~ cyl
make_formula(disp, cyl, am, drat)
#> disp ~ cyl + am + drat
make_formula(disp, cyl, am, drat, op = "*")
#> disp ~ cyl * am * drat
使用表达式的一大优点是它对小 bobby 表具有鲁棒性 ( https://xkcd.com/327/ ):
# User inputs are always interpreted as symbols (variable name)
make_formula(disp, `I(file.remove('~'))`)
#> disp ~ `I(file.remove('~'))`
# With `paste()` + `parse()` user inputs are interpreted as arbitrary code
reformulate(c("foo", "I(file.remove('~'))"))
#> ~foo + I(file.remove("~"))
关于r - 使用NSE构造公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63623330/