Good ways to define functions inside function in R

后端 未结 1 1228
旧时难觅i
旧时难觅i 2021-02-19 12:42

In R, when want to use one/multiple functions inside another function, maybe there are two ways. An example function can be:

Method 1:

m         


        
1条回答
  •  天涯浪人
    2021-02-19 13:26

    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.

    0 讨论(0)
提交回复
热议问题