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

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

Another option is:

#!/usr/bin/Rscript

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

It's a lot of work, but I finally got it (and posted at Rosetta Code).

This example exports a function called meaningOfLife. When the script is run by itself, it runs main. When imported by another R file, it does not run main.

#!/usr/bin/Rscript

meaningOfLife <- function() {
    42
}

main <- function(program, args) {
    cat("Main: The meaning of life is", meaningOfLife(), "\n")
}

getProgram <- function(args) {
    sub("--file=", "", args[grep("--file=", args)])
}

args <- commandArgs(trailingOnly = FALSE)
program <- getProgram(args)

if (length(program) > 0 && length(grep("scriptedmain", program)) > 0) {
    main(program, args)
    q("no")
}

You could pass arguments into R, and if an argument is present run main(). More on arguments here: http://yangfeng.wordpress.com/2009/09/03/including-arguments-in-r-cmd-batch-mode/

Tags:

Python

R