I am still new to R and right now I am trying to make my own function that I pass a dataframe and column name to and it outputs a plot. I want to do something like this, but I guess I am doing something wrong. Assume the dataframe's name is my_dataframe, the column is Age, and grouped by Species. I also want the title to be "age" in this example. Then:
makePlot <- function(X,col1,col2) {
p1 <- ggplot(X, aes(x = col1, fill = col2, y = col2)) + geom_point(aes(color = col2)) +
labs(x = 'Label_x', y = 'Label_y', title = col1)
return(p1)
}
make_rainplot(my_dataframe, Age, Species)
Thanks!
I have searched online but haven't found an explanation of how to do this.
Apart from the mismatch between function name and call pointed out by @YBS, your function tries to evaluate (here: find the object named) e.g. Age without success, because there's no such object outside my_dataframe
.
To be able to use unquoted object names as arguments as used from the tidyverse, you can delay evaluation, e. g. with ensym
:
makePlot2 <- function(X, col1, col2) {
col1 <- ensym(col1) ## ensym: don't go looking for Age yet
col2 <- ensym(col2)
ggplot(X, aes(x = !!col1, ## !!: now try to find Age (within X)
fill = !!col2, y = !!col2)) +
geom_point(aes(color = !!col2)) +
labs(x = 'Label_x', y = 'Label_y', title = col1)
}