问题
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?
回答1:
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))))
来源:https://stackoverflow.com/questions/34922586/r-make-function-robust-to-both-standard-and-non-standard-evaluation