Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently partially apply a function in R?

Suppose I have a function in R that takes multiple arguments, and I'd like to reduce it to a function of fewer arguments by setting some of the arguments to pre-specified values. I'm trying to figure out what is the best way to do this is in R.

For example, suppose I have a function

f <- function(a,b,c,d){a+b+c+d} 

I'd like to create or find a function partial that would do the following

partial <- function(f, ...){ #fill in code here } new_f <- partial(f, a=1, c= 2) 

new_f would be a function of b and d and would return 1+b+2+d

In python I would do

from functools import partial  def f(a,b,c,d):     return a+b+c+d  new_f = partial(f, a=1, c= 2) 

I'm actually doing this repeatedly and so I need for this to be as efficient as possible. Can anyone point me to the most efficient way to do this? Right now the best I can do is

partial <- function(f, ...){     z <- list(...)     formals(f) [names(z)] <- z     f } 

Can anyone let me know of a faster way or the best way to do this? This is simply too slow.

like image 943
k13 Avatar asked Aug 24 '15 03:08

k13


1 Answers

You could roll your own without too much coding using do.call:

partial <- function(f, ...) {   l <- list(...)   function(...) {     do.call(f, c(l, list(...)))   } } 

Basically partial returns a function that stores f as well as the originally provided arguments (stored in list l). When this function is called, it is passed both the arguments in l and any additional arguments. Here it is in action:

f <- function(a, b, c, d) a+b+c+d p <- partial(f, a=2, c=3) p(b=0, d=1) # [1] 6 
like image 89
josliber Avatar answered Sep 20 '22 23:09

josliber