Search code examples
rvariablesscopeprivate

How to create R functions with private variables?


How do I create a set of R functions that all access the same private variable?

Let's say I want to create readSetting(key) and writeSetting(key,value) functions that both operate on the same hidden list settings. If I try it like so...

local( {
  settings <- list()
  readSetting <<- function ( key ) settings[[key]]
  writeSetting <<- function ( key, value ) settings[[key]] = value
} )

...then readSetting and writeSetting are not visible outside of the local call. If I want them to be visible there, I have to first assign

readSetting <- writeSetting <- NULL

outside the local call. There must be a better way, because my code isn't DRY if I have to say in two different ways which variables are public.

(The context of this work is that I'm developing an R package, and this code will be in an auxiliary file loaded into the main file via source.)

This question is related to How to limit the scope of the variables used in a script? but the answers there do not solve my problem.


Solution

  • You can simulate somthing like that using R6Class package and the following very rough code:

    Privates <- R6Class("Privates",
                    public=list(
                         readSetting = function(key) {
                           private$settings[[key]]
                         },
                         writeSetting = function(key,value) {
                           private$settings[[key]] <<- value
                         }
                       ),
                    private=list(
                      settings = list()
                    )
    )
    a <- Privates$new()
    a$writeSetting("a",4)
    a$readSetting("a")
    

    Directly reading o setting the a$setting would not work.