I'm looking for a better way to organize my R code. Ideally I'm hoping to
In Python, the two goals can be achieved easily by:
def main():
...
def helper_func(x,y):
...
if __name__ == '__main__':
main()
Is it possible in R? Any advice on making it similar to this if not possible?
To your two points:
1) Since scripts are run top to bottom in a command-line fashion, anything you put at the bottom of a script will not be available to lines run above it. You can put auxillary functions in a different file and source it at the top of your "main" file.
2) Anything done in a function will be forgotten by the end:
> a = 2
> f = function(x) x <- x + 2
> b = f(a)
> b
[1] 4
> a
[1] 2
Alternatively, you can specify the environment you want to use anywhere:
> CustomEnv = new.env()
> assign("a", 2, envir = CustomEnv)
> a = 3
> a
[1] 3
> get("a", CustomEnv)
[1] 2
See ?environment
for more details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With