简体   繁体   中英

How to have helper function inherit variables from main function

I would like to set up a function bar() which relies on a helper function foo() . I am struggling to figure out the cleanest way to setup the variable definitions so I don't have to repeat the definitions in both foo() and bar() .

This seems like it should work but does not:

# helper function
foo <- function() {
 (a + b)/(c - d)
}

# main function
bar <- function(a, b, c, d) {
 z <- foo()
 z * 3
}

bar(a = 1, b = 2, c = 3, d =  4)

This works, but feels repetitive in the function definitions:

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


# main function
bar <- function(a, b, c, d) {
  z <- foo(a, b, c, d)
  z * 3
}

bar(a = 1, b = 2, c = 3, d = 4)

It works to assign the variables globally first, but not ideal:

a <- 1
b <- 2
c <- 3
d <- 4 

foo <- function() {
  (a + b)/(c - d)
}

# main function
bar <- function(a, b, c, d) {
  z <- foo()
  z * 3
}

bar(a = a, b = b, c = c, d =  d)

Is there a way to force the helper function to recognize the variables defined in the main function?

If you define foo in bar then foo() will look up for a , b , c , and d in the environment in which it is defined.

bar <- function(a, b, c, d) {

  foo <- function() {
    (a + b)/(c - d)
  }

  z <- foo()
  z * 3
}

Result

bar(a = 1, b = 2, c = 3, d =  4)
# -9

You can read more about it here: http://adv-r.had.co.nz/Functions.html#lexical-scoping

"... look inside the current function, then where that function was defined, and so on, all the way up to the global environment, and then on to other loaded packages."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM