0

Within ggplot2 and dplyr, functions do not require the column name of the variable to be quoted. Here are some examples:

# A plot example
library(ggplot2)
ggplot(mtcars, aes(mpg, cyl)) +
  geom_point()


# A dplyr example
library(dplyr)
mtcars %>%
  select(cyl)

However, if we try and directly replicate this in a function, it will complain that the unqouted object cannot be found:

foo <- function(df, x){
   df %>%
    select(x)    
}

foo(mtcars, cyl)

Error in FUN(X[[i]], ...) : object 'cyl' not found

How can the behaviour of these packages be replicated within my own functions, so that adding unquoted variables does not result in the above error?


I know we can use the underscore version of functions in dplyr to use character strings, or aes_string() within ggplot. For example:

foo2 <- function(df, x){    
  df %>%
    select_(x)      
}

foo(mtcars, "cyl")

I was hoping to find a solution which is consistent with the way it is done in these packages. I have looked a bit through the source code on GitHub, but it has only added to the confusion.

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
  • This? https://stackoverflow.com/questions/49645557/function-graph-with-dplyr/49646363#49646363 – Roman Apr 23 '18 at 11:17

1 Answers1

3

You can use quosures to achieve this. See this excellent article for more info on how it works and how to use it

foo <- function(df, x){

    x <- enquo(x)

    df %>%
      select(!!x)    
}
Relasta
  • 1,066
  • 8
  • 8