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