R 获取调用函数的参数类;“一旦删除”;

R 获取调用函数的参数类;“一旦删除”;,r,R,这是一个“语言计算”的问题,我的技能充其量也不算高。我正在编写一个函数来检查输入参数的类。以下是函数: chkArgs <- function() { # Get args of the function that called this function # stackoverflow.com/q/17256834/633251 args <- as.list(match.call(definition = sys.function(-1),

这是一个“语言计算”的问题,我的技能充其量也不算高。我正在编写一个函数来检查输入参数的类。以下是函数:

chkArgs <- function() {

    # Get args of the function that called this function
    # stackoverflow.com/q/17256834/633251
    args <- as.list(match.call(definition = sys.function(-1),
        call = sys.call(-1)))[-1]

    print(data.frame(cls = unlist(lapply(args, class)))) # for debugging only

    if (class(eval(args[["x"]])) != "integer")
        stop ("Argument 'x' was not an integer or not found")
    if (class(eval(args[["y"]])) != "integer")
        stop ("Argument 'y' was not an integer or not found")
}
testFunc <- function(x = 1L, y = 1L){ chkArgs(); x + y }
现在,如果我们间接调用
chkArgs
,或“一旦删除”,如下所示:

testFunc2 <- function(x = 1L, y = 1L){
    chkArgs()
    testFunc(x, y) # also calls chkArg
}

testFunc2(1L, 1L)

如何使chkArgs间接工作?

您可以使用

fargs <- function(n) { mget(names(formals(sys.function(n))), sys.frame(n), inherits=TRUE); }
这两个案例现在都已结案


最初编写的主要问题似乎是,内部检查只将
x
y
视为符号,因为它们在
eval
的直接环境中就是符号。使用
mget
inherits
将向上搜索帧,直到解析出一个值。

谢谢!它在我提供的玩具示例中起作用,在更复杂的实际软件包中起作用。更精简的代码总是更好。我将
fargs
放在
chkArgs
的主体中,以保持它的紧凑性,并且它也可以工作。我必须学习法格斯才能学到更多,但我能够继续前进。再次感谢。
> testFunc2(1L, 1L)
      cls
x integer
y integer
   cls
x name
y name
Error in eval(args[["x"]]) : object 'x' not found
fargs <- function(n) { mget(names(formals(sys.function(n))), sys.frame(n), inherits=TRUE); }
chkArgs <- function() {

    args <- fargs(-2);  # 2 because the helper function fargs is yet another level down

    if (class(args$x) != "integer")
        stop ("Argument 'x' was not an integer or not found")
    if (class(args$y) != "integer")
        stop ("Argument 'y' was not an integer or not found")

    return(args);
}