Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to ggplot in a wrapper

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.

Lets say for example, we consider the below MWE.

#Load Required libraries.
library(ggplot2)

##My Wrapper Function.
mywrapper <- function(data,xcol,ycol,colorVar){
  writeLines("This is my wrapper")
  plot <- ggplot(data=data,aes(x=xcol,y=ycol,color=colorVar)) + geom_point()
  print(plot)
  return(plot)
}

Dummy Data:

##Demo Data
myData <- data.frame(x=0,y=0,c="Color Series")

Existing Usage which executes without hassle:

##Example of Original Function Usage, which executes as expected
plot <- ggplot(data=myData,aes(x=x,y=y,color=c)) + geom_point()
print(plot)

Objective usage syntax:

##Example of Intended Usage, which Throws Error ----- "object 'xcol' not found"
mywrapper(data=myData,xcol=x,ycol=y,colorVar=c)

The above gives an example of the 'original' usage by the ggplot2 package, and, how I would like to wrap it up in another function. The wrapper however, throws an error.

I am sure this applies to many other applications, and it has probably been answered a thousand times, however, I am not sure what this subject is 'called' within R.

like image 825
Nicholas Hamilton Avatar asked Apr 30 '13 08:04

Nicholas Hamilton


1 Answers

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.

like image 81
Ben Avatar answered Sep 22 '22 05:09

Ben