Lesson contents

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

  1. Start with 1, 2, 3
  2. Do this Use median from stats
  3. Result 2
The two colons select a function from its package. The middle of these three numbers is 2.
Lesson.R
cat(stats::median(c(1, 2, 3)))
Output
2
Advertisements

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.

Room capacity: 8 seats. Already booked: 3 seats. Helper returns: 5 free seats.
Share a room-capacity calculation

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
boxes.R
remaining <- function(capacity, used) {
  capacity - used
}
lesson.R
boxes <- new.env()
sys.source("boxes.R", envir = boxes)
cat(boxes$remaining(8, 3), "\n", sep = "")
Output
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.

An Introduction to R

Related tags

  • R
  • modules
  • source files
  • imports