pass character strings to ggplot2 within a function

Solution 1:

There's the aes_string function, that I don't really see given prominence, which does exactly this:

FUN <- function(dat, x, y) {
    ggplot(dat, aes_string(x = x, y = y)) +
        geom_point()
}

FUN(mtcars, "mpg", "hp")

Solution 2:

It is now recommended to use .data pronoun

FUN <- function(dat, x, y) {
  ggplot(dat, aes(x = .data[[x]], y = .data[[y]])) +
    geom_point()
}

FUN(mtcars, "mpg", "hp")

enter image description here

Couple of other alternatives -

#Using get
FUN <- function(dat, x, y) {
  ggplot(dat, aes(x = get(x), y = get(y))) +
    geom_point()
}

#Using sym

FUN <- function(dat, x, y) {
  ggplot(dat, aes(x = !!sym(x), y = !!sym(y))) +
    geom_point()
}