[R] chaining closure arguments on-the-fly
Duncan Murdoch
murdoch@dunc@n @end|ng |rom gm@||@com
Sat Jun 20 15:00:06 CEST 2020
On 20/06/2020 7:15 a.m., Benjamin Tyner wrote:
> Greetings,
>
> Occasionally, I desire to call a function with one argument set to equal
> to another. Here is a toy example:
>
> f <- function(x, y) {
>
> x + y
> }
>
> f(x = 3, y = x) # Error in f(x = 3, y = x) : object 'x' not found
>
> So far, the most concise way I found to accomplish this is:
>
> f(x = 3, y = local(sys.frame(1)$x)) # evaluates to 6
>
> but I dislike this solution because local() creates a new environment.
> Surely there must be a better way?
>
> Note: I'm not interested in solutions that require modifying or currying f.
How about
g <- function(x, y = x) {
f(x, y)
}
g(x = 3)
or even
yEqualsX <- function(f) function(x, y = x) f(x, y)
yEqualsX(f)(x = 3)
These are a lot like currying, but aren't currying, so they may be
acceptable to you. Personally I'd choose the first one.
Duncan Murdoch
More information about the R-help
mailing list