johnramey

Don't think. Compute.

Converting a String to a Variable Name On-The-Fly and Vice-versa in R

with 8 comments

Recently, I had a professor ask me how to take a string and convert it to an R variable name on-the-fly. One possible way is:

x <- 42
eval(parse(text = "x"))
[1] 42

Now, suppose we want to go the other way. The trick is just as simple:

x <- 42
deparse(substitute(x))
[1] "x"
Did you like this? Share it:

Written by ramhiser

December 28th, 2010 at 8:32 pm

Posted in r

Tagged with

  • http://www.s-anand.net/ Anand S

    get(“x”) would return the value 42 as well.

  • Liviu

    There is an easier way:
    > x get(‘x’)
    [1] 42

    For info, you can:
    > assign(‘y’, 42)
    > get(‘y’)
    [1] 42

    But beware of the following fortune (although I never understood the underlying logic):
    > fortune(‘never use the assign’)

    The only people who should use the assign function are those who fully
    understand why you should never use the assign function.
    — Greg Snow
    R-help (July 2009)

  • Liviu

    The blog ate my assignment operator. Maybe this will please it:
    > x = 42
    > get(‘x’)
    [1] 42

  • JG

    What’s wrong wtih using ‘get(“x”)’?

  • ramhiser

    Well, if I’m trying to impress a professor, I can’t just use a function as easy to remember as get(), right? LOL

    Actually, I had forgotten about that one. Thanks for reminding me!

  • ramhiser

    Actually, there is an issue with get. My professor was trying to use this in context of lists. Consider the following list:

    x < - list(y = 42, z = 13)
    > x
    $y
    [1] 42

    $z
    [1] 13

    > get(“x$z”)
    Error in get(“x$z”) : object ‘x$z’ not found

    If I run the same code with eval and parse, then here’s the output:

    eval(parse(text=”x$z”))
    [1] 13

  • Harlan

    That works, but it’s still not a great idea to use eval() directly. This works:

    > get(‘x’)[['z']]
    [1] 13

  • Rich

    I think get() only works for variables, not for other expressions. That’s what happened w/ your list example. However, you can do:

    > get(“x”)$z
    [1] 13