I'm trying to learn S3 by using a single function which will create different plots depending on the class of the aes(x) supplied - if x is a factor then geom_boxplot
plot, if it's numeric then geom_point
library(ggplot2)
library(glue)
library(rlang)
myplot <- function(data, x, y) {
UseMethod("myplot", x)
}
# the default myplot behavior
# we're going to define what to do when x isn't a numeric or factor
# print error: x column is of class ____
myplot.default <- function(data, x, y) {
abort(glue(
"Can't use myplot because {deparse(substitute(x))} is of type ",
glue_collapse(class(x), "/")
))
}
# when x is a factor
myplot.factor <- function(data, x, y ) {
ggplot(data, aes(x = x, y = y)) +
geom_boxplot()
}
# when x is a numeric
myplot.numeric <- function(data, x, y) {
ggplot(data, aes(x = x, y = y)) +
geom_point()
}
And this works:
myplot(iris, iris$Species, iris$Sepal.Length)
myplot(iris, iris$Sepal.Width, iris$Sepal.Length)
# test that character will return default behavior
# as expected trying to run this on a character
# results in the default behavior
iris2 <- mutate_if(iris, is.factor, as.character)
myplot(iris2, iris2$Species, iris2$Sepal.Length)
But I want this to work:
myplot(iris, Species, Sepal.Length)
I've tried endless combinations of quo
enquo
deparse
get
- you name it but I still have gaps in my rlang understanding. Any help appreciated!!