I need to wrap ggplot2 into another function, and want to be able to parse variables in the same manner that they are accepted, can someone steer me in the correct direction
The problem here is that ggplot looks for a column
named xcol
in the data object. I would recommend to switch to using aes_string
and passing the column names you want to map using a string, e.g.:
mywrapper(data = myData, xcol = "x", ycol = "y", colorVar = "c")
And modify your wrapper accordingly:
mywrapper <- function(data, xcol, ycol, colorVar) {
writeLines("This is my wrapper")
plot <- ggplot(data = data, aes_string(x = xcol, y = ycol, color = colorVar)) + geom_point()
print(plot)
return(plot)
}
Some remarks:
x = 1
, for me this greatly improves the readability. Without spaces the code looks like a big block.This is just an addition to the original answer, and I do know that this is quite an old post, but just as an addition:
The original answer provides the following code to execute the wrapper:
mywrapper(data = "myData", xcol = "x", ycol = "y", colorVar = "c")
Here, data
is provided as a character string. To my knowledge this will not execute correctly. Only the variables within the aes_string
are provided as character strings, while the data
object is passed to the wrapper as an object.