Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an R equivalent of the pythonic "if __name__ == "__main__": main()"?

Tags:

python

r

The objective is to have two simple ways to source some code, say func.R, containing a function. Calling R CMD BATCH func.R initializes the function and evaluates is. Within a session, issuing source("func.R") simply initializes the function. Any idea?

like image 816
gappy Avatar asked Jun 03 '10 17:06

gappy


People also ask

Is if name == Main necessary?

The Reason Behind if __name__ == '__main__' in Python You might have seen this one before: the syntax which often gets ignored because it doesn't seem to hinder the execution of your code. It may not seem necessary, but that's only if you're working with a single Python file.

What is if name == Main in Python?

Python files can act as either reusable modules, or as standalone programs. if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.

What does __ main __ mean in Python?

In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.

What is __ name __ in Python?

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.


2 Answers

I think that the interactive() function might work.

This function returns TRUE when R is being used interactively and FALSE otherwise. So just use if (interactive())

i.e. the equivalent is

if (!interactive()) {   main() } 
like image 175
Harlan Avatar answered Sep 19 '22 08:09

Harlan


Another option is:

#!/usr/bin/Rscript  # runs only when script is run by itself if (sys.nframe() == 0){ # ... do main stuff } 
like image 36
edwindj Avatar answered Sep 19 '22 08:09

edwindj