Cast function argument as a character string?

Ray*_*Ray 18 r

超级快速的问题......

如何获取某个特定函数(用户定义的)参数并将其转换为字符串?

如果是一个简单的例子,

foo <- function(x) { ... }
Run Code Online (Sandbox Code Playgroud)

我想简单地返回x的对象名称.所以,

foo(testing123)
Run Code Online (Sandbox Code Playgroud)

返回"testing123"(并且testing123可能只是一些随机数字向量)

如果之前已经问过这个问题,我会道歉 - 搜索,但找不到它!谢谢!!

JD *_*ong 35

foo <- function(x) deparse(substitute(x))
Run Code Online (Sandbox Code Playgroud)


Spa*_*man 18

元答案:如果你知道R做某事你想做,请检查来源.例如,你可能已经发现了plot(foo)棒'foo' ylab,所以情节可以做到.怎么样?从查看代码开始:

> 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")
}
Run Code Online (Sandbox Code Playgroud)

还有一些deparse(substitute(x))魔力.