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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With