[英]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
理想情况下,我希望
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.