简体   繁体   English

R是否具有与python,C中的main函数类似的东西?

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

I'm looking for a better way to organize my R code. 我正在寻找一种更好的方法来组织我的R代码。 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: 在Python中,这两个目标可以通过以下方式轻松实现:

def main():
...

def helper_func(x,y):
...

if __name__ == '__main__':
    main()

Is it possible in R? 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. 1)由于脚本以命令行方式从上到下运行,因此放在脚本底部的任何内容都不可用于在其上运行的行。 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: 2)在函数中完成的任何事情都将被遗忘:

> 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 有关详细信息,请参阅?environment

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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