[R] Turning a variable name into a function argument

David Winsemius dwinsemius at comcast.net
Tue Jun 28 18:20:13 CEST 2016


> On Jun 27, 2016, at 6:12 PM, KMNanus <kmnanus at gmail.com> wrote:
> 
> I’m inexperience but am trying to get my head around using functions to make a number of ggplots easier to do.  
> 
> I have a function that creates a ggplot taking one input variable as an argument. The variable name is shorthand for the actual variable (variable name = tue, Actual name = Tuesday).  Since I want to use the actual variable name in ylab and ggtitle, I’d like to add a second argument, new.name, to the function which would allow me to utilize both inputs as arguments but have not been successful.  I tried creating a function within the function to accomplish this, using deparse(substitute(new.name))and also using the code you see below.
> 
> 
> myfun <- function(myvar, new.name){
>  function(new.name){return(as.character(substitute(new.name)))}
>  ggplot(b12.2, aes(x= games,  y = myvar, col = Group))+
>  geom_point() + 
>  geom_line()+
>  xlab("Minimum Games" ) +
>  ylab(paste(new.name, “Average Change"))+
>  ggtitle(new.name, "Change \n as a Function of Minimum Number of Games”)+
>  theme_bw()
> 
> When call myfun(myvar, new.name), I get an error msg “new.name is not found” whether I call new.name or Tuesday.

Q1: At the moment we have no idea _how_ you might be "calling" this function. We also do not know what might be assigned to `myvar` or `new.name` in the calling environment. Sounds unlikely that you are typing:

myfun(myvar, new.name)  ## ?, so was there a loop/lapply calling method?


Q2: You should not imagine that the inner anonymous function would be altering the value of `new.name`. (That function is only defined and never called, and even if it were called, it would not change the value of the `new.name` in the calling environment.)

Since more than 12 hours have passed with no response, we can surmise that many people have passed the question over after concluding there was an incomplete problem description. You should post code that can be cut-pasted into a session and produce the error you are getting. It would include data setup and a loop or loop equivalent to show how the function is being called.

-- 
David.


> 
> I want ggplot to automatically insert Tuesday into ylab and ggtitle.
> 
> Can anyone help me with this?  Thanks for your patience.
> 
> Ken
> kmnanus at gmail.com
> 914-450-0816 (tel)
> 347-730-4813 (fax)
> 
> 
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list