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

后端 未结 5 892
孤独总比滥情好
孤独总比滥情好 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

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

提交回复
热议问题