R passing a function argument to ggplot

81 Views Asked by At

I'm trying to pass a function argument (or parameter) to a ggplot - here's a dummy dataset to show/ test

test <- data.frame(id=c(1,2,3,4,5), 
                   base=c(230,365,390,201,298), 
                   heig=c(200,310,90,100, 91), 
                   widt=c(21,75,22,46,51))

fun1 <- function(va1,va2){
  ggplot(data=test,mapping=aes(va1, va2)) + geom_point()
}

fun1(base,heig)

I get an error:

Error in `geom_point()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `FUN()`:
! object 'base' not found
Run `rlang::last_trace()` to see where the error occurred.

I tried {{}}, [[]] and other combinations inside the ggplot in order to call the function param to no avail.

2

There are 2 best solutions below

1
P. Luchs On BEST ANSWER

You can use enquo like so:

library(ggplot2)
library(rlang)

fun1 <- function(va1,va2) {
  va1 <- enquo(va1)
  va2 <- enquo(va2)

  ggplot2::ggplot(data=test,mapping=aes(!!va1, !!va2)) + 
    geom_point()
}

From the help page of the "Tidy eval helpers":

(You can find it with: ?enquo):

enquo() and enquos() delay the execution of one or several function arguments. The former returns a single expression, the latter returns a list of expressions. Once defused, expressions will no longer evaluate on their own. They must be injected back into an evaluation context with ⁠!!⁠ (for a single expression) and ⁠!!!⁠ (for a list of expressions).

0
M-- On

We can use {{ var }}:

library(ggplot2)
library(rlang)

fun1 <- function(va1,va2){
  ggplot(data=test, mapping=aes({{va1}}, {{va2}})) + geom_point()
}

fun1(base, heig)

Or using base::match.call and base::eval (this will change the axes labels):

library(ggplot2)

fun1 <- function(va1,va2){
  arg <- match.call()
  ggplot(data=test, mapping=aes(eval(arg$va1), eval(arg$va2))) + geom_point()
}

fun1(base, heig)

Created on 2024-02-01 with reprex v2.0.2