Use main function in R

BlueFeet picture BlueFeet · Oct 28, 2015 · Viewed 11.2k times · Source

I've been using R for 4 months now, and I really hope there is a way to use main function as in other languages (C++, Python...)

The main reason I want to do this is that all the variables I use in a R script are global variables that can potentially pollute the namespace of the functions I defined in the same script:

f <- function(x) {
  x + a
}
a <- 50
f(5)

For me, this is just a personal preference. I'm a sloppy programmer and I want to prevent myself from making silly mistakes.

I can surely define main <- function() {}, but I want to know if there is anything similar to this:

if __name__ == "__main__": 
    main()

(In this Python script, if the function name is main, then run main() to call the main function.)

Answer

Leif Andersen picture Leif Andersen · Oct 28, 2015

So, it's not quite the same as __name__ == "__main__", but you might find the interactive function interesting here. Which returns TRUE if you are in an interactive mode.

So you can do something like this:

main <- function() {
    ....
}

if(!interactive()) {
    main()
}

This is a bit different though because it will always run if it's required from a script.