R make function robust to both standard and non-standard evaluation

本秂侑毒 提交于 2019-12-24 01:08:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!