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
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()
}
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")
}
Another option is:
#!/usr/bin/Rscript
# runs only when script is run by itself
if (sys.nframe() == 0){
# ... do main stuff
}
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.
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/