Michael Harper
Michael Harper

Reputation: 15369

How do ggplot and dplyr select unquoted variables in function

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.

Upvotes: 0

Views: 530

Answers (1)

Relasta
Relasta

Reputation: 1106

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)    
}

Upvotes: 3

Related Questions