Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast function argument as a character string?

Tags:

r

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!!

like image 772
Ray Avatar asked Nov 05 '10 17:11

Ray


3 Answers

foo <- function(x) deparse(substitute(x))
like image 184
JD Long Avatar answered Nov 06 '22 04:11

JD Long


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.

like image 25
Spacedman Avatar answered Nov 06 '22 03:11

Spacedman


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

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

Well that's easy...

like image 29
Ray Avatar answered Nov 06 '22 04:11

Ray