代码之家  ›  专栏  ›  技术社区  ›  Ray

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

r
  •  17
  • Ray  · 技术社区  · 14 年前

    快速提问…

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

    如果举个简单的例子,

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

    我只想返回x的对象名。所以,

    foo(testing123)
    

    收益率 "testing123" (测试123可能只是一些随机数字向量)

    如果之前有人问过这个问题,请道歉——搜索过,但找不到!谢谢!!

    3 回复  |  直到 11 年前
        1
  •  32
  •   JD Long    14 年前
    foo <- function(x) deparse(substitute(x))
    
        2
  •  17
  •   Gavin Simpson    11 年前

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

    deparse(substitute(x))

        3
  •  2
  •   Ray    14 年前

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