我正在尝试使用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
使用表达式的一大优势在于,它对于小型鲍比表(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("~"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句