Don't think. Compute.

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

with 10 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
[1] "x"
Did you like this? Share it:

Written by ramhiser

December 28th, 2010 at 8:32 pm

Posted in r

Tagged with

  • 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
    [1] 42

    [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:

    [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

  • bandhakavi

    is there a way to convert some text into a function/ method call similarly? I am trying to dynamically call an S3 method name without relying on the generic – I want to . For ex.
    df = data.frame()
    ## and then something like the code below which should actually call summary.dataframe() ##method
    eval(parse(paste(paste(“summary”,class(df),sep = “.”),”()”,sep = “”)))

  • Vanessa Klaas

    Hi, what if this x is the parameter of a function:

    myFunc <- function(x) {


    I would like to have output "var", not "x"
    Is this possible?