将函数参数转换为字符串?

时间:2010-11-05 17:47:51

标签: r

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

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

如果是一个简单的例子,

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

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

foo(testing123)

返回"testing123"(测试123可能只是一些随机数字向量)

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

3 个答案:

答案 0 :(得分:32)

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

答案 1 :(得分:17)

元答案:如果你知道R做某事而你想做,请检查来源。例如,您可能已经发现plot(foo)中的ylab棒'foo',因此情节可以执行此操作。怎么样?首先看一下代码:

> 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")
}

还有一些deparse(substitute(x))魔法。

答案 2 :(得分:2)

哎呀,显然我的搜索力度不够......

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

那很容易......