作为函数的一部分,我想输出所有参数及其值的列表,包括默认值.例如,具有以下参数的函数:
foo <- function(x=NULL,y=NULL,z=2) {
#formals()
#as.list(match.call())[-1]
#some other function?....
}
Run Code Online (Sandbox Code Playgroud)
提供输出:
> foo(x=4)
$x
[1] 4
$y
NULL
$z
[1] 2
Run Code Online (Sandbox Code Playgroud)
formals在调用函数时,不会更新以提供values参数值.match.call确实如此,但不提供参数的默认值.那里有另一个功能可以提供我想要的输出吗?
Rol*_*and 26
希望这不会导致龙.
foo <- function(x=NULL,y=NULL,z=2) {
mget(names(formals()),sys.frame(sys.nframe()))
}
foo(x=4)
$x
[1] 4
$y
NULL
$z
[1] 2
print(foo(x=4))
$x
[1] 4
$y
NULL
$z
[1] 2
Run Code Online (Sandbox Code Playgroud)
ags*_*udy 11
你可以混合使用2 match.call和formals
foo <- function(x=NULL,y=NULL,z=2)
{
ll <- as.list(match.call())[-1] ##
myfor <- formals(foo) ## formals with default arguments
for ( v in names(myfor)){
if (!(v %in% names(ll)))
ll <- append(ll,myfor[v]) ## if arg is missing I add it
}
ll
}
Run Code Online (Sandbox Code Playgroud)
例如 :
foo(y=2)
$y
[1] 2
$x
NULL
$z
[1] 2
> foo(y=2,x=1)
$x
[1] 1
$y
[1] 2
$z
[1] 2
Run Code Online (Sandbox Code Playgroud)
这是尝试将此逻辑包装在可重用的函数中,而不是match.call:
match.call.defaults <- function(...) {
call <- evalq(match.call(expand.dots = FALSE), parent.frame(1))
formals <- evalq(formals(), parent.frame(1))
for(i in setdiff(names(formals), names(call)))
call[i] <- list( formals[[i]] )
match.call(sys.function(sys.parent()), call)
}
Run Code Online (Sandbox Code Playgroud)
它看起来像是有效的:
foo <- function(x=NULL,y=NULL,z=2,...) {
match.call.defaults()
}
> foo(nugan='hand', x=4)
foo(x = 4, y = NULL, z = 2, ... = pairlist(nugan = "hand"))
Run Code Online (Sandbox Code Playgroud)
foo <- function(x=NULL,y=NULL,z=2) {
X <- list(x,y,z); names(X) <- names(formals()); X
}
z <- foo(4)
z
#------
$x
[1] 4
$y
NULL
$z
[1] 4
Run Code Online (Sandbox Code Playgroud)