简体   繁体   中英

Cast function argument as a character string?

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

foo <- function(x) deparse(substitute(x))

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.

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

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

Well that's easy...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM