[R] Get inside a function the name of a variable called as argument?

Duncan Murdoch murdoch at stats.uwo.ca
Tue Apr 29 16:34:02 CEST 2008


On 29/04/2008 9:53 AM, Julien Roux wrote:
> Hi list,
> I created a function to plot my data:
> plot_function(vector)
> I want to write the name of the argument vector in the legend/title of 
> the plot.
> For example if I call:
>  > plot_function(my_vector)
> I want "my_vector" to be written in the legend or title and so retrieve 
> the name of this object as a string.
> 
> Is it possible to achieve this?

Yes.  If the argument name is arg in the function definition, then 
substitute(arg) gives the expression that was passed, and 
deparse(substitute(arg)) converts it into a string to use in a title.

e.g.

 > plot_function <- function(arg) {
+   deparse(substitute(arg))
+ }
 > plot_function(my_vector)
[1] "my_vector"

Duncan Murdoch

> Thanks a lot for your help
> Julien
>



More information about the R-help mailing list