22

Super quick question...

How do you take a some particular function's (user-defined) argument and cast it as a character-string?

If for a simple example,

foo <- function(x) { ... }

I want to simply return x's object name. So,

foo(testing123)

returns "testing123" (and testing123 could just be some random numeric vector)

Apologies if this question has been asked before--searched, but couldn't find it! Thanks!!

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Ray
  • 3,137
  • 8
  • 32
  • 59

3 Answers3

42
foo <- function(x) deparse(substitute(x))
JD Long
  • 59,675
  • 58
  • 202
  • 294
20

Meta-answer: if you know R does something and you want to do it, check the source. For example, you may have spotted that plot(foo) sticks 'foo' in the ylab, so plot can do it. How? Start by looking at the code:

> plot
function (x, y, ...) 
{
    if (is.function(x) && is.null(attr(x, "class"))) {
        if (missing(y)) 
            y <- NULL
        hasylab <- function(...) !all(is.na(pmatch(names(list(...)), 
            "ylab")))
        if (hasylab(...)) 
            plot.function(x, y, ...)
        else plot.function(x, y, ylab = paste(deparse(substitute(x)), 
            "(x)"), ...)
    }
    else UseMethod("plot")
}

And there's some deparse(substitute(x)) magic.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
Spacedman
  • 92,590
  • 12
  • 140
  • 224
2

Whoops, apparently I didn't search hard enough...

foo <- function(x) {return(as.character(substitute(x)))}

Well that's easy...

Ray
  • 3,137
  • 8
  • 32
  • 59
  • `deparse(substitute(x))` would be the usual way of doing this, as per JD's answer. Compare your version with JD's on this `foo(testing * bar)` to see why. – Gavin Simpson Nov 05 '10 at 18:24