问题描述
背景
我对使用do.call
使用一个列表将参数传递给两个函数感兴趣。 do.call
解决方案应忽略未使用的参数。
示例
my_sum <- function(a,b) {
a + b
}
my_exp <- function(c,d) {
c^d
}
args_to_use <- as.list(1:4)
names(args_to_use) <- letters[1:4]
my_wrapper <- function(fun_args = args_to_use) {
res_one <- do.call(my_sum,fun_args)
res_two <- do.call(my_exp,fun_args)
res_one + res_two
}
自然地,该示例失败,因为多余的参数被传递给两个函数。
所需结果
my_wrapper_two <- function(fun_args = args_to_use) {
res_one <- do.call(my_sum,fun_args[1:2]) # Only a,b
res_two <- do.call(my_exp,fun_args[3:4]) # Only c,d
res_one + res_two
}
my_wrapper_two()
# 84
寻求解决方案
注释
我正在考虑的一种方法是使用names(formals(my_exp))
创建所需的参数列表,如下所示:
my_wrapper_three <- function(fun_args = args_to_use) {
res_one <- do.call(my_sum,fun_args[names(formals(my_sum))])
res_two <- do.call(my_exp,fun_args[names(formals(my_exp))])
res_one + res_two
}
my_wrapper_three()
这看起来不太优雅,我想知道是否有更智能的解决方案?
更新
我提出的解决方案如下:
do_call_on_existing <- function(fun,args_list) {
fun_args <- names(formals(fun))
viable_args <- args_list[fun_args]
viable_args <- Filter(Negate(is.null),viable_args)
do.call(fun,viable_args)
}
Filter
/ Negate
位可防止函数失败,其中my_sum
可能会有多余的参数,从而导致参数列表返回null
元素。因此代码可以正常工作:
my_sum <- function(a = 999,b = 999,c = 999) {a + b + c}
my_nms <- list(a = 1,b = 2)
do_call_on_existing(my_sum,my_nms)
解决方法
尝试一下( public void oc_chooseImage(View view) {
Intent intent = new Intent ( );
intent.setType ( "image/*" );
intent.setAction ( Intent.ACTION_GET_CONTENT );
startActivityForResult (intent,1);
}
@Override
protected void onActivityResult(int requestCode,int resultCode,@Nullable Intent data) {
super.onActivityResult ( requestCode,resultCode,data );
if(requestCode == 1 && resultCode==RESULT_OK && data != null && data.getData () != null)
{
imageUri = data.getData ();
mv_logo.setImageURI ( imageUri );
nav_logo.setImageURI ( imageUri );
}
}
允许您将任意数量的参数传递到...
中,但根据您的定义,仅使用my_sum
和a
):
b