我正在尝试编写一个函数来接受data.frame(x)和a column.该函数对x执行一些计算,然后返回另一个data.frame.我坚持使用最佳实践方法将列名传递给函数.
两个最小的例子fun1和fun2下面产生所需的结果,能够执行操作x$column,使用max(),例如,然而,两者都依赖于看似(至少对我而言)不优雅
substitute()可能eval() fun1 <- function(x, column){
do.call("max", list(substitute(x[a], list(a = column))))
}
fun2 <- function(x, column){
max(eval((substitute(x[a], list(a = column)))))
}
df <- data.frame(B = rnorm(10))
fun1(df, "B")
fun2(df, "B")
Run Code Online (Sandbox Code Playgroud)
我希望能够将该功能称为fun(df, B)例如.我考虑但尚未尝试的其他选项:
column为列号的整数.我认为这会避免substitute().理想情况下,该功能可以接受.with(x, get(column))但是,即使它有效,我认为这仍然需要 substitute formula()和match.call(),我都没有多少经验.子问题:do.call()首选eval()?