r - 使用NSE构造公式

标签 r tidyeval non-standard-evaluation

我正在尝试使用 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/

相关文章:

r - 在 lapply 中使用 data.table 时 get 中的第一个参数无效

r - 如何用 `eval`函数调用 `with`?

r - 在函数内的lm()中调用权重无法正确评估

r - 在州名称上显示与美国各州对应的值

python - 如何像 R 一样在 scikit-learn 中获得回归摘要?

r - 在 Fantasy Football 阵容优化器中添加 Flex 位置

r - 如何在 R ggplot 图形的函数中包含查找表和/或将某些字符串传递到图形中?

r - 如何制作同时支持带引号和不带引号的参数的 tidyverse 函数?

r - 使用 dplyr (tidyeval) 运行选定列的函数

r - curl 整洁的评估编程,具有多个输入和跨列的自定义函数