2

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?

talat
  • 68,970
  • 21
  • 126
  • 157
roming
  • 1,165
  • 1
  • 9
  • 22

1 Answers1

4

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))))
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
  • As a side note, I'm not a big pipe fan, but you could probably pipe your code in the function in a more `dplyr` idiomatic way- that will make hadley very happy. – David Arenburg Jan 21 '16 at 12:31
  • not sure how to use the dplyr pipe ```%>%``` in functions. Like that: `dplyr::"%>%"`? – roming Jan 21 '16 at 12:38
  • Once you have `dplyr` loaded you don't need to use `dplyr::`, unless you want it to work without loading `dplyr`? – David Arenburg Jan 21 '16 at 12:39
  • 1
    Well, since I - of course - want to make hadley very happy, I used this way of referring to functions since it is recommended [here](http://r-pkgs.had.co.nz/namespace.html#imports) – roming Jan 21 '16 at 12:42
  • You have a point there. Anyway, I was mainly joking- it's your choice. – David Arenburg Jan 21 '16 at 12:51
  • It's also worth keeping in mind that: "If you are using functions repeatedly, you can avoid `::` by importing the function with `@importFrom pgk fun`. This also has a small performance benefit, because `::` adds approximately 5 µs to function evaluation time." (From the second paragraph of the R functions section) – NGaffney Jan 22 '16 at 01:42