Quantcast

how to convert variable name to string?

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

how to convert variable name to string?

Jinsong Zhao-2
Hi there,

In the following function:

demo.plot <- function( obj ) plot(1:5, obj, xlab = "x")

Then, I use this function as following:

y <- rnorm(5)
demo.plot(y)

It will produce a plot with ylab = "obj", however, I hope to get a plot
with ylab = "y".

Is it possible to convert object/variable name y to a string "y", so I
can set it in demo.plot():

demo.plot <- function( obj ){
    lab.y <- obj.name.2.string(obj) #### I need obj.name.2.string()
    plot(1:5, obj, xlab = "x", ylab = lab.y)
}

I don't know how to define the function obj.name.2.string.

Any suggestion will be greatly appreciated.

Regards,
Jinsong

______________________________________________
[hidden email] mailing list
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.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: how to convert variable name to string?

Peter Dalgaard-2

On Aug 14, 2012, at 16:54 , Jinsong Zhao wrote:

> Hi there,
>
> In the following function:
>
> demo.plot <- function( obj ) plot(1:5, obj, xlab = "x")
>
> Then, I use this function as following:
>
> y <- rnorm(5)
> demo.plot(y)
>
> It will produce a plot with ylab = "obj", however, I hope to get a plot with ylab = "y".
>
> Is it possible to convert object/variable name y to a string "y", so I can set it in demo.plot():
>
> demo.plot <- function( obj ){
>   lab.y <- obj.name.2.string(obj) #### I need obj.name.2.string()
>   plot(1:5, obj, xlab = "x", ylab = lab.y)
> }
>
> I don't know how to define the function obj.name.2.string.
>
> Any suggestion will be greatly appreciated.

The standard trick involves deparse(substitute(....)). Take a look inside plot.default.


>
> Regards,
> Jinsong
>
> ______________________________________________
> [hidden email] mailing list
> 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.

--
Peter Dalgaard, Professor
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: [hidden email]  Priv: [hidden email]

______________________________________________
[hidden email] mailing list
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.
Loading...