R — Organizing code across files
In R, sys.source can evaluate a helper file in a chosen environment. The entry script can then retrieve the function from that environment.
A simple example
Call a function from a package
- Start with 1, 2, 3
- Do this Use median from stats
- Result 2
cat(stats::median(c(1, 2, 3)))
2
Share a function between source files
Run the entry script from the folder containing both files. sys.source evaluates definitions in the supplied environment. The caller accesses the helper through that environment.
A club ticket desk has eight seats and three bookings. Keep the calculation in a helper file so both the booking screen and the check-in screen can use it. With the same inputs, each reports five places left.
Run the example
R 4. Run these commands from the directory containing the example.
Rscript lesson.R
remaining <- function(capacity, used) {
capacity - used
}
boxes <- new.env()
sys.source("boxes.R", envir = boxes)
cat(boxes$remaining(8, 3), "\n", sep = "")
5
Create the files with the names shown and run the command from their common project folder. The entry point gives the helper a capacity of 8 and a used count of 3. The helper returns 5.
Try it yourself
Change the used count from 3 to 8 in the caller.
Check your answer
Running the same command prints 0. No change to the helper is needed.