Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does R have something similar to main function as in python, C?

Tags:

r

I'm looking for a better way to organize my R code. Ideally I'm hoping to

  • Put all auxiliary functions at the end of the script. It will help me to focus on the main part of the code without being distracted by lots of helper functions at the beginning of the script.
  • Allow each variable to only exist in certain scope. e.g If I accidentally assign values to certain variables, I don't want these variables to be picked up by functions defined later than them and make a mess.

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?

like image 275
BlueFeet Avatar asked Nov 09 '22 06:11

BlueFeet


1 Answers

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

like image 167
Señor O Avatar answered Nov 15 '22 07:11

Señor O