2

I would like to pass the same argument to several nested functions. For example, given 2 functions:

 fun1 = function(x){x^2}
 fun2 = function(x,FUN,...) { x + FUN(...) }

I would like to implement something like this:

 fun2(x=10,FUN=fun1)  ## this returns error

In this example, I would like to get an output of 10 + 10^2 = 110

I have seen this answered question: Passing arbitrary arguments to multiple nested functions in R but I specifically wish to pass the same argument to multiple nested functions.

1

3 Answers 3

2

In your example, ... is what follows the FUN argument, i.e. nothing. You could play with sys.call to reuse the arguments, e.g.:

 fun2 <- function(FUN, x, ...) {
     cl <- match.call(expand.dots = TRUE) # unevaluated expression `fun2(x=10,FUN=fun1)`
# Note: sys.call would work only if the arguments were named
     cl[[1]] <- cl$FUN # substitute `fun2`. Now cl is `fun1(x=10,FUN=fun1)`
     cl$FUN <- NULL # remove FUN argument. Now cl is `fun1(x=10)`
     result.of.FUN <- eval.parent(cl) # evaluate the modified expression
     x + result.of.FUN
 }
Sign up to request clarification or add additional context in comments.

Comments

1

The xs are not the same in both functions.

Consider this:

fun1 <- function(y) y^2 
fun2 <- function(x,FUN) x + FUN(x) 

> fun2(x=10, FUN=fun1)
[1] 110

You see, if you don't pass the argument with FUN(x), fun1() doesn't recognize the x=10.

1 Comment

I like what you're doing here but have 2 comments. (i) defining fun1 in terms of x (i.e. fun1 <- function(x) {x^2}) will return the correct result and (ii) I am looking for a more general answer. The way you define fun2 indicates that the input function (FUN) will always depend on x, which isn't necessarily true. It would be nice to have a solution where the input function (FUN) doesn't need to have its inputs defined explicitly.
0

Another somewhat less robust but perhaps simpler solution as compared Kamil's, is to rely on the argument order of the defined functions as such:

fun1 = function(x){x^2}
fun2 = function(x,FUN,...) { x + FUN(...) }

Then running fun2 as:

 > fun2(x=10,FUN=fun1,10)
 [1] 110 

This again relies on knowing the order of the function arguments, which is somewhat dangerous.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.