Stefan Klocke
Stefan Klocke

Reputation: 139

Let inner function use arguments of outer function

I'm having trouble finding out the following: There's an outer function inside which an inner function is called. The inner function is recursive. Both functions share some common arguments a, b, c, as I want the outer function to pass these arguments through to inner. a, b, c are essentially option parameters for inner, which need to be accessible from outside.

A drastically simplified version could look like this

inner <- function(a, b, c, d, i = 0) {
  # Something
  inner(a = left, b = right, c, d, i = i + 1)
}

outer <- function(a, b, c, r, t) {
  d <- r^2
  inner(a = a, b = b, c = c, d = d)
}

Now, the call of inner inside outer seems a bit bulky to me. I'd like a, b, c to be passed to inner "automatically" instead of having to explicitly passing them as arguments again, since they are constant option parameters. The key may be ellipsis/... but unfortunately I couldn't manage to find the answer ...

Help is greatly appreciated!

Cheers, Stefan

Upvotes: 0

Views: 1685

Answers (2)

Melissa Key
Melissa Key

Reputation: 4551

Another method is to write

outer <- function(r, t, ...) {
  d <- r^2
  inner(d = d, ...)
}

Passing values for a, b, and c to outer will cause these to get automatically passed to the inner function. The only drawback to this method is that it's not clear from the outer function that values for a, b, and c are required.

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 269441

1) Define the inner function inside the outer function and the inner function will have access to the outer function's variables. Here inner uses a from outer even though a was not passed to inner.

outer <- function(a, x) {
  inner <- function(y) {
    a + y
  }

  inner(2 * x)
}

# test
outer(10, 100)
## [1] 210

2) Alternately, inject inner into outer like this:

inner <- function(y) {
  a + y
}

outer <- function(a, x) {
  environment(inner) <- environment()    
  inner(2 * x)
}

# test
outer(10, 100)
## [1] 210

Upvotes: 3

Related Questions