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

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?


Solution 1:

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()
}

Solution 2:

Another option is:

#!/usr/bin/Rscript

# runs only when script is run by itself
if (sys.nframe() == 0){
# ... do main stuff
}