如何绑定函数参数 [英] How to bind function arguments

查看:87
本文介绍了如何绑定函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将部分参数绑定/应用到R中的函数?

How do I partially bind/apply arguments to a function in R?

这就是我走了多远,然后我意识到这种方法行不通...

This is how far I got, then I realized that this approach doesn't work...

bind <- function(fun,...)
{
  argNames <- names(formals(fun))
  bindedArgs <- list(...)
  bindedNames <- names(bindedArgs)
  function(argNames[!argNames %in% bindedArgs])
   {
   #TODO
  }
}

谢谢!

推荐答案

您是否尝试过查看roxygen的Curry函数?

Have you tried looking at roxygen's Curry function?

> library(roxygen) 
> Curry
function (FUN, ...) 
{
    .orig = list(...)
    function(...) do.call(FUN, c(.orig, list(...)))
}
<environment: namespace:roxygen>

示例用法:

> aplusb <- function(a,b) {
+   a + 2*b
+ }
> oneplusb <- Curry(aplusb,1)
> oneplusb(2)
[1] 5

简洁地定义了Curry以接受已命名或未命名的参数,但是通过formal()分配将fun应用于参数的一部分要求更复杂的匹配以模拟相同的功能.例如:

Curry is concisely defined to accept named or unnamed arguments, but partial application of fun to arguments by way of formal() assignment requires more sophisticated matching to emulate the same functionality. For instance:

> bind <- function(fun,...)
+ {
+   argNames <- names(formals(fun))
+   boundArgs <- list(...)
+   boundNames <- names(boundArgs)
+   if(is.null(boundNames)) {
+     formals(fun)[1:length(boundArgs)] <- boundArgs
+   } else {
+     formals(fun)[match(names(boundArgs),argNames)] <- boundArgs
+   }
+   fun
+ }
> oneplusb <- bind(aplusb,1)
> oneplusb(2)
Error in 2 * b : 'b' is missing

由于此函数中的第一个参数仍为a,因此需要指定将哪个2参数用于(b=),或将其作为第二个参数传递.

Because the first argument in this function is still a, you need to specify which argument 2 is intended for (b=), or pass it as the second argument.

> oneplusb
function (a = 1, b) 
{
    a + 2 * b
}
> oneplusb(b=2) ## or oneplusb(,2)
[1] 5

这篇关于如何绑定函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆