Reputation: 4243
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?
Upvotes: 3
Views: 590
Reputation: 26343
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."
Upvotes: 4