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),
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
间接工作?
解决方案
您可以使用以下方法解析父函数的形式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);
}
这两种情况现在都检查出来了。
最初编写的主要问题似乎是内部检查只是将x
和y
视为符号,因为这就是它们在eval
. 使用mget
withinherits
将搜索帧,直到解析出一个值。
推荐阅读
- c# - 调试 Xamarin Form SignalR 客户端 C# 时出现警告消息“存在冲突”
- javascript - Javascript - 直接访问元素或设置变量更快?
- python - Python Tensorflow - InvalidArgumentError:无法计算 BatchMatMulV2 作为输入
- python - 选择数据框
- c++ - 关于双向gRPC流写入的问题
- java - SpringBoot Mockito 测试 - 来自 MockitoSessionBuilder 的 mockitoSession NoSuchMethod
- spring-boot - Thymeleaf引擎进程中如何使用图片资源
- uwp - 构建版本时可以保留 FutureAccessList 吗?
- macos - 使用 Scons 安装 RosettaCommon 时出错
- java - Servlet 未执行