5

In Matlab if I have a function f such as the signature is f(a,b,c), I can make a function which has only one variable b, which would call f with a fixed a=a1 and c=c1:

g = @(b) f(a1, b, c1);

Is there an equivalent in R, or do I just need to redefine a new function ?

BlueTrin
  • 9,610
  • 12
  • 49
  • 78

2 Answers2

7

There is also the convenient functional::Curry functional:

f <- function(a, b, c) {a + b + c}
f(1, 2, 3)
# [1] 6

library(functional)
g <- Curry(f, a = a1, c = c1)
g(b=2)
# [1] 6
g(2)
# [1] 6

I think an important difference with @NPE's solution is that the definition of g using Curry does not mention b. So you might prefer this approach when the number of arguments in f becomes large.

flodel
  • 87,577
  • 21
  • 185
  • 223
  • 1
    There's also `pryr::partial` and in `ptools`, `%<<%`, `%>>%` and `%()%`. It's not clear how partial evaluation and lazy evaluation of arguments should interact, and each package takes a slightly different approach. – hadley Mar 26 '13 at 13:17
5
g <- function(b) f(a1, b, c1)
NPE
  • 486,780
  • 108
  • 951
  • 1,012