Easy to use option settings management with the 'settings' package

Last week I released a new package called settings. It grew out of my frustration built up during several small projects where I'm generating heavily parameterized d3/js output. What I wanted was support to

  • define a whole bunch of option settings with default values;
  • be able to set them globally or locally within a function or object without explicitly re-assigning every setting;
  • reset (global) option settings to default with ease.

Turns out, the first and last wishes on my list are fulfilled with the futile.options package. I really wanted the inheritance features though so I experimented a bunch of times with different implementations. Most of those were based on reference classes holding (global) option settings. In the end I chose a functional approach, inspired by futile.options. I feel this approach is both lightweight (the package's code basically fits readably on an A4 page) and elegant[1].

I'm going to give a quick glance of the package here, and refer to the package vignette for extensive examples.

You can define an options manager like this.

library(settings)
opt <- options_manager(foo=0,bar=1)

opt is a function that acts like R's default options function.

# get option settings:
> opt('foo')
[1] 0
# change option settings
opt(bar=10)
opt()
> opt(bar=10,foo=6)
> opt()
$foo
[1] 6

$bar
[1] 10

The cool thing is that you can reset it to defaults like this.

> reset(opt)
> opt()
$foo
[1] 0

$bar
[1] 1

The second cool thing is that you can create a copy, where the copy has the same defaults but new current settings.

> loc_opt <- clone_and_merge(opt,foo=7)
> loc_opt()
$foo
[1] 7

$bar
[1] 1
# loc_opt can be reset locally:
> reset(loc_opt)
> loc_opt()
$foo
[1] 0

$bar
[1] 1

Resetting or otherwise altering loc_opt does not affect the global options set in opt. Of course, loc_opt can be cloned again and again.
This stuff is useful when you write a function and you want to merge options in dot-dot-dot arguments with global options. For example

# user may or may not want to add options like foo=10 when calling 'myfunc'
myfunc <- function(x,...){

  # merge user-defined options with global options in globally defined 'opt'
  loc_opt <- clone_and_merge(opt,...)
  # use local options
  loc_opt('foo') + loc_opt('bar') * x
}

For more examples, including on how to use this in S4 or reference classes, or how to use settings as an options manager in a package, please see the package vignette. As always, the code is available on github.

[1] Well, it hurts to say there's a bit of abstraction leakage here: there are two option names that cannot be used: .__defaults and .__reset, but the package provides methods to protect against that.

This entry was posted in programming, R. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

*