在执行期间显示函数的实际参数列表

Ani*_*iko 4 r function-call

我试图显示调用函数时提供的参数的实际值.`match.call'按照我想要的方式执行某些操作,但它不会对变量进行求值.例如

foo <- function(x) match.call()
foo(2)
Run Code Online (Sandbox Code Playgroud)

版画

foo(x = 2)
Run Code Online (Sandbox Code Playgroud)

我很高兴.然而:

xxx <- 2
foo(xxx)
Run Code Online (Sandbox Code Playgroud)

将打印

foo(x = xxx)
Run Code Online (Sandbox Code Playgroud)

而不是foo(x = 2)我想拥有它.

我曾尝试各种组合substitute,eval和公司,但没有成功的.

fab*_*ans 7

我写了一个函数expand.call(),它可以做你想要的(我想......).实际上,它做了一点:

#' Return a call in which all of the arguments which were supplied
#' or have presets are specified by their full names and supplied
#' or default values.
#'  
#' @param definition a function. See \code{\link[base]{match.call}}.
#' @param call an unevaluated call to the function specified by definition.
#'  See \code{\link[base]{match.call}}.
#' @param expand.dots logical. Should arguments matching ... in the call be 
#'  included or left as a ... argument? See \code{\link[base]{match.call}}.
#' @param doEval logical, defaults to TRUE. Should function arguments be 
#'  evaluated in the returned call or not?
#'
#' @return An object of class call. 
#' @author fabians
#' @seealso \code{\link[base]{match.call}}
expand.call <- function(definition=NULL,
         call=sys.call(sys.parent(1)),
         expand.dots = TRUE,
         doEval=TRUE)
{

    safeDeparse <- function(expr){
        #rm line breaks, whitespace             
        ret <- paste(deparse(expr), collapse="")
        return(gsub("[[:space:]][[:space:]]+", " ", ret))
    }

    call <- .Internal(match.call(definition, call, expand.dots))

    #supplied args:
    ans <- as.list(call)
    if(doEval & length(ans) > 1) {
      for(i in 2:length(ans)) ans[[i]] <- eval(ans[[i]])
    }

    #possible args:
    frmls <- formals(safeDeparse(ans[[1]]))
    #remove formal args with no presets:
    frmls <- frmls[!sapply(frmls, is.symbol)]

    add <- which(!(names(frmls) %in% names(ans)))
    return(as.call(c(ans, frmls[add])))
}
Run Code Online (Sandbox Code Playgroud)

如果你需要保留一些关于调用的更多信息或者更好地格式化它,你通常会使用它作为match.call()的替代,例如:

foo <- function(x, bar="bar", gnurp=10, ...) {
    call <- expand.call(...)
    return(call)
}   

> foo(2)
foo(x = 2, bar = "bar", gnurp = 10)

> xxx <- 2
> foo(xxx)
foo(x = 2, bar = "bar", gnurp = 10)

> foo(xxx, b="bbbb")
foo(x = 2, bar = "bbbb", gnurp = 10)

> foo(xxx, b="bbbb", doEval=FALSE)
foo(x = xxx, bar = "bbbb", doEval = FALSE, gnurp = 10)
Run Code Online (Sandbox Code Playgroud)

也许你可以用它来解决你的问题.