Good ways to define functions inside function in R

2020-07-03 06:41发布

问题:

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?

回答1:

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-coded n value.

> n = 100
> f1 = make.power(2)
> f1(2)
[1] 4
> n = 1
> f1(2)
[1] 4

Example 2 will not, instead it will rely on the global definition of n.

> n = 1
> make.power2(2)
[1] 2
> n = 100
> make.power2(2)
[1] 1.267651e+30

As functions get more complex, so will the scoping issues. The link David Robinson provides in the comments is a great resource.



标签: r function