I don't know much about S3, but have been running into issues with names, so I thought I'd try things that have worked for me before. I'm sure this is hacky, but it seems to work, although I haven't tested it further than you see here:
library(ggplot2)
library(glue)
library(rlang)
myplot <- function(data, x, y) {
if(is.call(enexpr(x))){
UseMethod("myplot", x)
} else {
x <- enexpr(x)
UseMethod("myplot", data[[as_name(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) {
if(is.symbol(enexpr(x))){
x <- enexpr(x)
abort(glue(
"Can't use myplot because {deparse(substitute(x))} is of type ",
glue_collapse(class(data[[as_name(x)]]), "/")
))
} else {
}
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 ) {
if(is.symbol(enexpr(x))){
x <- enexpr(x)
} else {
x <- substitute(x)
}
y <- enexpr(y)
ggplot(data, aes(x = !!x, y = !!y)) +
geom_boxplot()
}
# when x is a numeric
myplot.numeric <- function(data, x, y) {
if(is.symbol(enexpr(x))){
x <- enexpr(x)
} else {
x <- substitute(x)
}
y <- enexpr(y)
ggplot(data, aes(x = !!x, y = !!y)) +
geom_point()
}
myplot(iris, iris$Species, iris$Sepal.Length)
myplot(iris, Species, iris$Sepal.Length)
myplot(iris, iris$Species, Sepal.Length)
myplot(iris, iris$Sepal.Width, iris$Sepal.Length)
myplot(iris, Species, iris$Sepal.Length)
myplot(iris, iris$Species, 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)
myplot(iris2, Species, iris2$Sepal.Length)
I'm not sure this helps you understand S3, but hopefully it helps some in terms of working with names.