Quite new to R, I am wondering if it is possible to shrink own blowed-up R scripts by packaging parts into sub scripts, like modules or global own functions. This is somewhat usual in other interpreter languages.
What is the best way split data-reading, plotting, designing, exporting, etc in different R modules?
Modular programming (also referred to as modular architecture) is a general programming concept. It involves separating a program's functions into independent pieces or building blocks, each containing all the parts needed to execute a single aspect of the functionality.
Modules can be used as stand alone, ad-hoc substitutes for a package or as a sub-unit within a package. When modules are defined inside of packages they act as bags of functions (like objects as in object-oriented-programming).
Examples of modular programming languages - All the object-oriented programming languages like C++, Java, etc., are modular programming languages.
Functional programming languages In R, this means that you can do many of the things with a function that you can do with a vector: you can assign them to variables, store them in lists, pass them as arguments to other functions, create them inside functions, and even return them as the result of a function.
There’s a package for exactly this purpose, called ‘box’.
The package provides a function box::use()
which replaces source
and library
in a smart manner.
source('x.r')
can simply be replaced by
box::use(./x)
# or:
box::use(./x[...]) # to attach all names
However, box::use()
does many things better than source
— for instance, you can organise your modules hierarchically inside a project, you can treat package and module code uniformly, you can document your module code, and more.
See the vignette for details.
The ‘box’ package was created precisely because I was unsatisfied with R’s support for modularisation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With