R function parameter question

Hi all,

I had a quick question about functions in R.

I'm wondering how to take the value of a parameter and use it inside ggplot AES.

Here's a description. I have a simple function that will take an input data set with pairs of x and y variables. The data set might also have multiple by variables (e.g. sex, or age for each row of x and y points). I want to be able to specify which variable in the function call the graph points should be colored by.

I know the below doesn't work because it is looking for an actual variable named byvar in the dataset, though what I really want is for the function to evaluate the value of the parameter and search for that value as a variable in the data frame.

I'm kind of new to R functions and would appreciate any help (even trying to google search for this is kind of awkward - I know the issue but I'm likely missing a key term in my search)


myfunc <- function(input, byvar) {

graph <- ggplot(data=input, aes(x=x,y=y)) +
         geom_point(data=input, size=3, aes(colour=byvar))

#Assume I have a data frame 'sample' with x, y and sex as columns
try1 <- myfunc(input=sample, byvar=sex)


Error in eval(expr, envir, enclose): object 'byvar' not found
Last edited:
If you want the value you're inputting to aes to be interpreted as a string then you probably want to use aes_string instead of aes
Thanks Dason! This definitely worked and pointed me in the right direction for other searches. I see that quite a lot has been written about writing functions that use ggplot2 now :)