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

后端 未结 5 893
孤独总比滥情好
孤独总比滥情好 2020-12-13 03:43

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 evaluat

相关标签:
5条回答
  • 2020-12-13 04:17

    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()
    }
    
    0 讨论(0)
  • 2020-12-13 04:17

    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")
    }
    
    0 讨论(0)
  • 2020-12-13 04:23

    Another option is:

    #!/usr/bin/Rscript
    
    # runs only when script is run by itself
    if (sys.nframe() == 0){
    # ... do main stuff
    }
    
    0 讨论(0)
  • 2020-12-13 04:23

    I asked a similar question, in an answer, Matthew Plourde suggested using getOption('run.main', default=TRUE) in the main script and then setting options(run.main=FALSE) before calling source(). This worked in my case.

    Otherwise a simpler pattern when you have an R script creating a bunch of functions and you want to write a few lines at the end of the script to experiment with the use of a function: place these extra lines in an if(FALSE){} block.

    0 讨论(0)
  • 2020-12-13 04:30

    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/

    0 讨论(0)
提交回复
热议问题