我寫了一個函數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])))
}
你通常會以此爲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)
也許你可以用它來解決你的問題。
哦,棘手!它解決了直接在'match.call()'上使用'eval'會再次調用該函數的問題。謝謝! – Aniko 2010-08-14 15:28:48