In R, when want to use one/multiple functions inside another function, maybe there are two ways. An example function can be:
Method 1:
make.power <- function(n) {
pow <- function(x) {
x^n
}
pow
}
Method 2:
make.power <- function(n) {
pow(n)
}
pow <- function(x) {
x^n
}
In my opinion (but I am not sure), the second method is a better way if you have lots of child functions for the parent one.
My questions are: 1) Are there any functional differences between the two ways? E.g., how the function will pass variables, or the relationship between the children and parent functions, etc..
2) which one might be a preferred one (maybe more computational efficient or structurally clear) for R?
If you are asking about the specific example you gave, this question does not seem too broad to me.
The main difference here is the evaluation of
n
. For example 1, the function that gets returned will essentially have a hard-codedn
value.Example 2 will not, instead it will rely on the global definition of
n
.As functions get more complex, so will the scoping issues. The link David Robinson provides in the comments is a great resource.