简体   繁体   中英

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

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. eg 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM