[Rd] Conventions: Use of globals and main functions

Cyclic Group Z_1 cyc||cgroup-z1 @end|ng |rom y@hoo@com
Mon Aug 26 01:09:57 CEST 2019



This is a fair point; structuring functions into packages is probably ultimately the gold standard for code organization in R. However, lexical scoping in R is really not much different than in other languages, such as Python, in which use of main functions and defining other named functions outside of main are encouraged. For example, in Scheme, from which R derives its scoping rules, the community generally organizes code with almost exclusively functions and few non-function global variables at top level. The common use of globals in R seems to be mostly a consequence of historical interactive use and, relatedly, an inherited practice from S.

It is true, though, that since anonymous functions (such as in lapply) play a large part in idiomatic R code, as you put it, "[l]exical scoping means that all of the problems of global variables are available to writers who use main()." Nevertheless, using a main function with other functions defined outside it seems like a good quick alternative that offers similar advantages to making a package when functions are tightly coupled to the script and the project may not be large or generalizable enough to warrant making a package.

Best,
CG



More information about the R-devel mailing list