我正在尝试编写一个函数来接受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()?
(有些相关的问题:在dplyr的重命名函数中输入新的列名作为字符串)
在dplyrchain(%>%)的中间,我想用旧名称的函数替换多个列名(使用tolower或gsub等)
library(tidyr); library(dplyr)
data(iris)
# This is what I want to do, but I'd like to use dplyr syntax
names(iris) <- tolower( gsub("\\.", "_", names(iris) ) )
glimpse(iris, 60)
# Observations: 150
# Variables:
# $ sepal_length (dbl) 5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6,...
# $ sepal_width (dbl) 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4,...
# $ petal_length (dbl) 1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4,...
# $ …Run Code Online (Sandbox Code Playgroud)