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

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

问题描述

如何将参数部分绑定/应用到 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天全站免登陆