gpt4 book ai didi

r - 在执行过程中显示函数的实际参数列表

转载 作者:行者123 更新时间:2023-12-04 22:51:59 26 4
gpt4 key购买 nike

我试图显示调用函数时提供的参数的实际值。 `match.call' 按照我想要的方式做一些事情,但它不评估变量。例如

foo <- function(x) match.call()
foo(2)

打印
foo(x = 2)

我对此很满意。然而:
xxx <- 2
foo(xxx)

将打印
foo(x = xxx)

而不是 foo(x = 2)因为我想拥有它。

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

最佳答案

不久前我写了一个函数 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)

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

关于r - 在执行过程中显示函数的实际参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3478923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com