Julien Roux
2008-Apr-29 13:53 UTC
[R] Get inside a function the name of a variable called as argument?
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? Thanks a lot for your help Julien -- Julien Roux, PhD student http://www.unil.ch/dee/page22707.html Department of Ecology and Evolution Biophore, University of Lausanne, 1015 Lausanne, Switzerland tel: +41 21 692 4221 fax: +41 21 692 4165
Hans Ekbrand
2008-Apr-29 14:30 UTC
[R] Get inside a function the name of a variable called as argument?
On Tue, Apr 29, 2008 at 03:53:02PM +0200, 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?While it might be possible, I think it would be better to use an extra argument for this: plot_function(my_vector, title = my_title) Functions should be general, and relying on the name of the variable makes your function less general. What if you in the future want to use plot_function with an anynmous vector created dynamically? e.g by combining two other vectors: plot_function(c(foo, bar)) -- Hans Ekbrand (http://sociologi.cjb.net) <hans at sociologi.cjb.net> GPG Fingerprint: 1408 C8D5 1E7D 4C9C C27E 014F 7C2C 872A 7050 614E -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 191 bytes Desc: Digital signature URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20080429/fa00352f/attachment.bin>
Duncan Murdoch
2008-Apr-29 14:34 UTC
[R] Get inside a function the name of a variable called as argument?
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 >