R使功能对标准和非标准评估都有效 [英] R make function robust to both standard and non-standard evaluation
问题描述
我有一些功能可以通过依赖 dplyr
的数据框架的用户定义的列
进行搜索。在下面的当前窗体中,它接受非标准评估中的列参数 - 不包括引号(例如方案
而不是场景$ c $
search_column< - function(df,column,string,fixed = TRUE){
df< - dplyr :: select_(df,deparse(substitute(column)))
df< - distinct(df)
return(grep(string,df [ 1]],fixed = fixed,value = TRUE))
}
有没有
如果用户输入列名称,即在标准或非标准评估中,我建议您简单地删除由 deparse
添加到字符串输入的额外引号,在这种情况下会导致相同的输出,您的代码将适用于任何输入
比较3个可能的输入
gsub('',, deparse(替代( MPG ))
[1]mpg
gsub('',,deparse(代替('mpg')))
[1]mpg
gsub(''',,deparse(substitute(mpg)))
[1]mpg
所以解决方案可能只是修改你的第一行到
df< - dplyr :: select_ (df,gsub(''',,deparse(substitute(column))))
I have a little function that searches though user defined column
of a dataframe relying on dplyr
. In the current form below it accepts the column argument in non-standard evaluation - without quotes (e.g. scenario
instead of "scenario"
in standard evaluation).
search_column <- function(df, column, string, fixed = TRUE){
df <- dplyr::select_(df, deparse(substitute(column)))
df <- distinct(df)
return(grep(string, df[[1]], fixed = fixed, value = TRUE))
}
Is there a way to make the function work no matter how the user enters the column name, i.e. in standard or non-standard evaluation?
I would suggest simply removing the additional quotes that being added by deparse
to a string input, in that case it will result in identical output and your code will work for any input
Compare 3 possible inputs
gsub('"', "", deparse(substitute("mpg")))
[1] "mpg"
gsub('"', "", deparse(substitute('mpg')))
[1] "mpg"
gsub('"', "", deparse(substitute(mpg)))
[1] "mpg"
So the solution could be to just modifying your first line to
df <- dplyr::select_(df, gsub('"', "", deparse(substitute(column))))
这篇关于R使功能对标准和非标准评估都有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!