R测试在评估之前传递给函数的函数参数
R Test parmeters of functions passed to a function before evaluation
我想构造一个函数(我们称它为 f()),它将获得两个参数
其他功能(f1(),f2())。 f1 和 f2 都有自己的参数。
我希望 f() 在评估 f1() 和 f2() 之前对传递的参数进行一些测试
以 f1() 和 f2() 为例,验证它们的名称是否相同。
简而言之,我想要这样的东西:
f<-function(f1(param),f2(param)){
f1Param<-#get the param argument of f1
f2Param<-#get the param argument of f2
stopifnot(identical(names(f1Param),names(f2Param)))
#evaluate f1(param) and f2(param) and do some opertaions on the outputs
}
但我不确定如何从 f1() 和 f2() 中提取参数然后获取它们
评估。
我看到了一些解决此问题的建议 match.call()
或 mget()。
但是,在此处给出的示例中,被调用函数所做的唯一事情就是 return 它的参数,
我实际上希望我的功能做一些事情。
有什么方法可以使用say, match.call() 来测试环境中的参数
调用函数(在我的示例中为 f()),然后决定是否基于计算 f1 和 f2
关于测试结果?
提前致谢
按照 Tensibai 的建议,您可以执行以下操作:
f <- function(f1, f2, f1Param, f2Param){
stopifnot(is.list(f1Param) && is.list(f2Param))
stopifnot(identical(names(f1Param),names(f2Param)))
do.call(f1, f1Param) == do.call(f2, f2Param)
}
例如:
> f(mean, mean, list(x = 1:10), list(x = 2:9))
[1] TRUE
> f(mean, mean, list(x = 1:10), list(y = 2:9))
# ERROR
我想构造一个函数(我们称它为 f()),它将获得两个参数 其他功能(f1(),f2())。 f1 和 f2 都有自己的参数。 我希望 f() 在评估 f1() 和 f2() 之前对传递的参数进行一些测试 以 f1() 和 f2() 为例,验证它们的名称是否相同。 简而言之,我想要这样的东西:
f<-function(f1(param),f2(param)){
f1Param<-#get the param argument of f1
f2Param<-#get the param argument of f2
stopifnot(identical(names(f1Param),names(f2Param)))
#evaluate f1(param) and f2(param) and do some opertaions on the outputs
}
但我不确定如何从 f1() 和 f2() 中提取参数然后获取它们 评估。 我看到了一些解决此问题的建议 match.call() 或 mget()。 但是,在此处给出的示例中,被调用函数所做的唯一事情就是 return 它的参数, 我实际上希望我的功能做一些事情。 有什么方法可以使用say, match.call() 来测试环境中的参数 调用函数(在我的示例中为 f()),然后决定是否基于计算 f1 和 f2 关于测试结果?
提前致谢
按照 Tensibai 的建议,您可以执行以下操作:
f <- function(f1, f2, f1Param, f2Param){
stopifnot(is.list(f1Param) && is.list(f2Param))
stopifnot(identical(names(f1Param),names(f2Param)))
do.call(f1, f1Param) == do.call(f2, f2Param)
}
例如:
> f(mean, mean, list(x = 1:10), list(x = 2:9))
[1] TRUE
> f(mean, mean, list(x = 1:10), list(y = 2:9))
# ERROR