Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind function arguments

Tags:

r

bind

apply

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
  }
}

Thanks!

like image 852
Cookie Avatar asked Dec 03 '22 08:12

Cookie


2 Answers

Here's a version of Curry that both preserves lazy evaluation of function argument, but constructs a function that prints moderately nicely:

Curry <- function(FUN, ...) {
  args <- match.call(expand.dots = FALSE)$...
  args$... <- as.name("...")

  env <- new.env(parent = parent.frame())

  if (is.name(FUN)) {
    fname <- FUN
  } else if (is.character(FUN)) {
    fname <- as.name(FUN)
  } else if (is.function(FUN)){
    fname <- as.name("FUN")
    env$FUN <- FUN
  } else {
    stop("FUN not function or name of function")
  }
  curry_call <- as.call(c(list(fname), args))

  f <- eval(call("function", as.pairlist(alist(... = )), curry_call))
  environment(f) <- env
  f
}

It basically works by generating an anonymous function in exactly the same way you would if you were constructing the partial binding yourself.

like image 55
hadley Avatar answered Dec 15 '22 06:12

hadley


Actually, this seems to work as a work around

bind <- function(fun,...)
{
  boundArgs <- list(...)
  formals(fun)[names(boundArgs)] <- boundArgs
  fun
}

However, ideally I want the bound arguments to disappear completely from the new function so that calls to the new function can happen with name specification, e.g. with add <- function(a,b) a+b I would like (bind(add,a=2))(1) to return 3.

like image 23
Cookie Avatar answered Dec 15 '22 05:12

Cookie