R — Named settings and locked bindings
An ordinary name in R can be reassigned. A private environment with a locked binding can protect a configuration setting from reassignment through that binding.
A simple example
Use a fixed value
- Start with Unit is 3
- Do this Multiply by 2
- Result 6
unit <- 3
cat(2 * unit, "\n", sep = "")
6
Name a fixed scheduling interval
Express a 30-minute slot in terms of a 15-minute base interval. Keep the slot count separate so different bookings can reuse the same rule. Lock only the base setting. The derived slot length remains a normal expression. Locking a binding to a mutable environment would still allow changes inside that environment.
The music room can be booked in 30-minute slots. A rehearsal needs three slots, so the calendar sets aside 90 minutes. Naming the slot length lets every booking use the same rule.
Run the example
Use R 4.x. Run these commands from the directory containing the example.
Rscript --vanilla Lesson.R
settings <- new.env(parent = emptyenv())
settings$base_minutes <- 15L
lockBinding("base_minutes", settings)
slot_minutes <- 2L * settings$base_minutes
booked_slots <- 3L
cat(sprintf("%d minutes\n", booked_slots * slot_minutes))
90 minutes
Two base intervals make each slot 30 minutes. A booking of three slots lasts 90 minutes.
Try it yourself
If the base interval changes to 10 minutes, how long is the same three-slot booking?
Check your answer
Each slot now lasts 20 minutes, so the booking lasts 60 minutes.