首页 > 解决方案 > 获取调用函数“一旦删除”的参数类

问题描述

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

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 }

这些电话:

testFunc(1L, 1L)
testFunc(3.0, 1L)
testFunc(x = 8L)

现在,如果我们chkArgs间接调用,或者“一旦删除”,如下:

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

testFunc2(1L, 1L)

我们得到这个输出:

> testFunc2(1L, 1L)
      cls
x integer
y integer
   cls
x name
y name
Error in eval(args[["x"]]) : object 'x' not found

我怎样才能chkArgs间接工作?

标签: r

解决方案


您可以使用以下方法解析父函数的形式n参数

fargs <- function(n) { mget(names(formals(sys.function(n))), sys.frame(n), inherits=TRUE); }

所以你chkArgs可以写成

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);
}

这两种情况现在都检查出来了。

最初编写的主要问题似乎是内部检查只是将xy视为符号,因为这就是它们在eval. 使用mgetwithinherits将搜索帧,直到解析出一个值。


推荐阅读