scope - Writing functions in R, keeping scoping in mind -
I often write functions that require viewing other objects in my environment. For example:
< Pre> & gt; A & lt; - 3 & gt; B & L; -3 & gt; X & lt; - 1: 5 & gt; Fn1 & lt; - Function (x, a, b) A + B + x> Fn2 & lt; - Function (x) a + b + x & gt; FN1 (X, A, B) [1] 7 8 9 10 11 & gt; As expected, both functions are similar because fn2
sees it a and b when it is executed. But whenever I start taking advantage of this, within 30 minutes I ask the function to make calls without any required variables (eg A or B). If I do not take advantage of it, then I think that I am passing unnecessarily around objects. Is it better to be clear about the requirement of the function? Or should it be taken care of through inline comments or other documents of the function? Is there a better way?
If I know that I need a function parameterized by some values and times- The bar is said to be, I avoid globs using the closure:
make.fn2
It cleverly refrains from referring to the global variable, instead a. And using the transport environment of B's function. . Modifications of the Global A and B are not unfinished side effects, when called FN2 example.
Comments
Post a Comment